一.vector的增删查改
1.下面我们看下push_back/pop_back 的代码实现
#include<iostream>
#include <vector>
using namespace std;
int main()
{
int a[] = { 1, 2, 3, 4 };
vector<int>v(a, a + sizeof(a)/sizeof(a[0]));
vector<int>::iterator it = v.begin();
while (it != v.end())
{
cout << *it << " ";
++it;
}
cout << endl;
v.pop_back();
v.pop_back();
it = v.begin();
while (it != v.end())
{
cout << *it << " ";
++it;
}
cout << endl;
system("pause");
return 0;
}
下面看下生成的可执行程序:
2.看下find/insert/erase的代码实现
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
vectorv(a, a + sizeof(a) / sizeof(a[0]));
//使用find 查找3所在位置的iterator
vector::iterator pos = find(v.begin(), v.end(), 3);
//在POS之前插入30
v.insert(pos, 30);
vector<int>::iterator it = v.begin();
while (it != v.end())
{
cout << *it << " ";
++it;
}
cout << endl;
pos = find(v.begin(), v.end(), 3);
//删除POS位置元素
v.erase(pos);
it = v.begin();
while (it != v.end())
{
cout << *it << " ";
++it;
}
cout << endl;
system("pause");
return 0;
}
3.operator[]+index 和 c++11中vector的新式for+auto的遍历
int main()
{
int a[] = { 1, 2, 3, 4 };
vectorv(a, a + sizeof(a) / sizeof(a[0]));
//通过[]读写第0个位置
v[0] = 10;
cout << v[0] << endl;
//通过[i]的方式遍历vector
for (size_t i = 0; i < v.size(); i++)
cout << v[i] << " ";
cout << endl;
vector<int>swapv;
swapv.swap(v);
cout << "v data:";
for (size_t i = 0; i < v.size(); ++i)
cout << v[i] << " ";
cout << endl;
cout << "swapv data:";
for (size_t i = 0; i < swapv.size(); ++i)
cout << swapv[i] << " ";
cout << endl;
//c++11支持新式范围for遍历
for (auto x : v)
cout << x << " ";
cout << endl;
system("pause");
return 0;
}
4.vector迭代器失效问题
int main()
{
vector<int>v{ 1, 2, 3, 4, 5 };
auto it = v.begin();
//将有效元素个数增加到100个,多出的位置用8填充,操作期间底层会扩容
v.resize(100, 8);
//reserve的作用就是改变扩容大小但不改变有效元素个数,操作期间会引起底层容量的改变
v.reserve(100);
//插入期间可能会引起扩容,而导致原空间被释放
//v.insert(v.begin(),0);
//v.push_back(8);
//给vector重新赋值,可能会引起底层容量改变
v.assign(100, 8);
//以上操作都有可能导致vector扩容,也就是说明vector底层原理空间被释放掉,
//而在打印时,it还使用的是释放之前的旧空间,对于it迭代器操作时,实际操作的是一块已经被释放的空间,而引起代码运行时崩溃。
//解决方案:在以上操作完成时如果想要继续通过迭代器操作vector中的元素,只需给it重新赋值即可
while (it != v.end())
{
cout << *it << " ";
++it;
}
cout << endl;
return 0;
}
迭代器失效问题解决方式:
如果想要继续通过迭代器操作vector中的元素,只需给it重新赋值即可