Vector用法介绍2

作者:哈哈小脸 | 创建时间: 2023-05-29
这篇文章的目的是为了介绍std::vector,如何恰当地使用它们的成员函数等操作。本文中还讨论了条件函数和函数指针在迭代算法中使用,如在remove_if()和for_each()中的使用。通过阅读这篇文章读者应该能够有效地使用vecto...
Vector用法介绍2

操作方法

vector的成员函数和操作 vector <Elem> c   创建一个空的vector。 vector <Elem> c1(c2) 用c2拷贝c1 vector <Elem> c(n) 创建一个vector,含有n个数据,数据均已缺省构造产生。 vector <Elem> c(n, elem) 创建一个含有n个elem拷贝的vector。 vector <Elem> c(beg,end) 创建一个以[beg;end)区间的vector。 c.~ vector <Elem>() 销毁所有数据,释放内存。

Vector操作 函数描述 operator[] 返回容器中指定位置的一个引用。 创建一个vector vector容器提供了多种创建方法,下面介绍几种常用的。 创建一个Widget类型的空的vector对象: vector<Widget> vWidgets; //     ------ //      | //      |- Since vector is a container, its member functions //         operate on iterators and the container itself so //         it can hold objects of any type. 创建一个包含500个Widget类型数据的vector: vector<Widget> vWidgets(500);

创建一个包含500个Widget类型数据的vector,并且都初始化为0: vector<Widget> vWidgets(500, Widget(0)); 创建一个Widget的拷贝: vector<Widget> vWidgetsFromAnother(vWidgets); 向vector添加一个数据 vector添加数据的缺省方法是push_back()。push_back()函数表示将数据添加到vector的尾部,并按需要来分配内存。例如:向vector<Widget>中添加10个数据,需要如下编写代码: for(int i= 0; i<10; i++) vWidgets.push_back(Widget(i));

方法/步骤2

获取vector中制定位置的数据 很多时候我们不必要知道vector里面有多少数据,vector里面的数据是动态分配的,使用push_back()的一系列分配空间常常决定于文件或一些数据源。如果你想知道vector存放了多少数据,你可以使用empty()。获取vector的大小,可以使用size()。例如,如果你想获取一个vector v的大小,但不知道它是否为空,或者已经包含了数据,如果为空想设置为-1,你可以使用下面的代码实现: int nSize = v.empty() ? -1 : static_cast<int>(v.size()); 访问vector中的数据

使用两种方法来访问vector。 1、   vector::at() 2、   vector::operator[] operator[]主要是为了与C语言进行兼容。它可以像C语言数组一样操作。但at()是我们的首选,因为at()进行了边界检查,如果访问超过了vector的范围,将抛出一个例外。由于operator[]容易造成一些错误,所有我们很少用它,下面进行验证一下: 分析下面的代码: vector<int> v; v.reserve(10); for(int i=0; i<7; i++) v.push_back(i); try { int iVal1 = v[7]; // not bounds checked - will not throw int iVal2 = v.at(7); // bounds checked - will throw if out of range } catch(const exception& e) { cout << e.what(); }

点击展开全文

更多推荐