vector不是一种数据类型,而是一个类模板,可用来定义任意多种数据类型。vector类型的每一种都指定了其保存元素的类型。因此,vector < int > 和 vector < string > 都是一种数据类型。
若要创建非空的vector对象,必须给出初始化元素的值。
方式说明vector < int > ivec1;//ivec1 holds objects of type intvector < int > ivec2(ivec1);//ok:copy elements if ivec1 into ivec2vector < string > sivec(ivec1);//error:svec holds strings, not ints如果没有指定元素的初始化式,那么标准库将自动提供一个元素初始值进行值初始化。
vector < int > fvec(10);//10 elements, each initialized to 0
使用 size_type 类型时,必须指出该类型是在哪里定义的。vector 类型总是包括 vector 的元素类型。 vector < int >::size_type // ok vector::size_type // error
// read words from the standard input and store them as elements in a vetor
string word; vector < string > text;// empty vector while (cin >> word){ text.push_back(word);// append word to text }C++程序猿习惯优先选用!=而不是<来编写循环判断条件。 在C++中有些数据结构(如vector) 可动态增长,故我们习惯于每次循环中测试size的当前值。
