Container--vector用法

来源:互联网 发布:网络暴力原因 编辑:程序博客网 时间:2024/05/06 01:20

1.Library vector Type

#include <vector>
using std::vector;
vector<int> ivec;               // ivec holds objects of type int
vector<Sales_item> Sales_vec;   // holds Sales_items

vector is not a type; it is a template that we can use to define any number of types. Each of vector type specifies an element type. Hence, vector<int> and vector<string> are types.

2.Defining and Initializing vectors

 Ways to Initialize a vector
vector<T> v1;    //vector that holds objects of type T;Default constructor v1 is empty
vector<T> v2(v1);  //v2 is a copy of v1
vector<T> v3(n, i);//v3 has n elements with value i
vector<T> v4(n);   //v4 has n copies of a value-initialized object
 
 Creating a Specified Number of Elements
vector<int> ivec1;           // ivec1 holds objects of type int
vector<int> ivec2(ivec1);    // ok: copy elements of ivec1 into ivec2
vector<string> svec(ivec1);  // error: svec holds strings, not ints
vector<int> ivec4(10, -1);       // 10 elements, each initialized to -1
vector<string> svec(10, "hi!");  // 10 strings, each initialized to "hi!"

 Value Initialization
vector<int> fvec(10); // 10 elements, each initialized to 0
vector<string> svec(10); // 10 elements, each an empty string

3.Operations on vectors

 vector Operations
v.empty() Returns true if v is empty; otherwise returns false
v.size() Returns number of elements in v
v.push_back(t) Adds element with value t to end of v
v[n]  Returns element at position n in v
v1 = v2  Replaces elements in v1 by a copy of elements in v2
v1 == v2 Returns TRue if v1 and v2 are equal
!=, <, <=,
>, and >= Have their normal meanings
 
 The size of a vector
vector<int>::size_type       // ok
vector::size_type            // error
 
 Adding Elements to a vector
 // read words from the standard input and store them as elements in a vector
     string word;
     vector<string> text;    // empty vector
     while (cin >> word) {
         text.push_back(word);     // append word to text
     }

 Subscripting a vector
// reset the elements in the vector to zero
     for (vector<int>::size_type ix = 0; ix != ivec.size(); ++ix)
         ivec[ix] = 0;
 
 Subscripting Does Not Add Elements
vector<int> ivec;   // empty vector
     for (vector<int>::size_type ix = 0; ix != 10; ++ix)
         ivec[ix] = ix; // disaster: ivec has no elements

The right way to write this loop would be
     for (vector<int>::size_type ix = 0; ix != 10; ++ix)
         ivec.push_back(ix);  // ok: adds new element with value ix