目录
1. vector的介绍
vector是模板实现的。
Vectors are sequence containers representing arrays that can change in size.
2. vector的使用
使用上分几大部分:默认成员函数,迭代器,容量相关,访问相关,修改。
2.1 构造函数
void test1() { //无参 vector<int> v1; //有参 vector<int> v2(10); //val的缺省值是0。 vector<int> v3(10, 1); //迭代器 vector<int> v4(v3.begin(), v3.end()); //拷贝构造 vector<int> v5(v4); }
2.2 遍历方式
1. 下标加[ ],2. 迭代器,3. 范围for。
void test2() { vector<int> v(10, 5); //下标+[] for (size_t i = 0; i < v.size(); i++) { cout << v[i] << " "; } cout << endl; //迭代器 vector<int>::iterator it = v.begin(); while (it != v.end()) { cout << *it << " "; it++; } cout << endl; //范围for for (auto e : v) { cout << e << " "; } cout << endl; }
2.3 reserve与resize
reserve改变容量。
预先开空间就用reserve,容量改变,有效个数不变。
resize改变有效个数。
【区别】
【扩容机制】
vs:1.5倍扩容,g++:2倍扩容
2.4 shrink_to_fit
缩容:将容量缩到和有效个数一样。
一般是异地缩容。
2.5 insert,erase,find
(1)在pos位置的元素前面插入val。
(2)在pos位置的元素前面插入n个val。
(3)在pos位置的元素前面插入一段迭代器区间。
注意:传入的是迭代器。
找到pos的位置需要借