标准库vector类型

xiaoxiao2021-02-28  104

vector不是一种数据类型,而是一个类模板,可用来定义任意多种数据类型。vector类型的每一种都指定了其保存元素的类型。因此,vector < int > 和 vector < string > 都是一种数据类型。

vector对象的定义和初始化

若要创建非空的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

vector对象的操作

操作说明v.empty()如果 v 为空,则返回 true,否则返回 false。v.size()返回 v 中字符的个数v.push_back(t)在 v 的末尾添加一个值为 t 的元素v[n]返回 v 中位置为 n 的字符v1 = v2把 v1 的元素替换为 v2 中元素的副本v1 == v2比较 v1 与 v2 的内容,相等则返回 true,否则返回 false!=,<, <=, >, and >=保持这些操作符惯有的含义

vector对象的size

使用 size_type 类型时,必须指出该类型是在哪里定义的。vector 类型总是包括 vector 的元素类型。 vector < int >::size_type // ok vector::size_type // error

向vector添加元素

// 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 }

vector的下标操作

for (int vector::size_type ix = 0;ix != ivec.size();++ix){ ivec[ix] = 0; }

C++程序猿习惯优先选用!=而不是<来编写循环判断条件。 在C++中有些数据结构(如vector) 可动态增长,故我们习惯于每次循环中测试size的当前值。

下标操作不添加元素

vector < int > ivec;// empty vetor for (vector < int >::size_type ix = 0;ix != 10;++ix){ ivec[ix] = ix;// disaster: ivec has no elements } for (vector < int >::size_type ix = 0;ix != 10;++ix){ ivec[ix].push_back(ix);// ok :adds new elements with value ix }
转载请注明原文地址: https://www.6miu.com/read-78862.html

最新回复(0)