c++编程实现如下要求:初始化一个vector容器(assign)并循环插入(insert或push back)10 个数据,分别利用下标和迭代器遍历输出所有数据。注意比较数据插入前和插入后容器的capacity变化。删除部分数据(erase或pop _back)。注意可能导致迭代器失效的问题,再次遍历输出所有数据(可以采用for _each与函数对象实现)。注意观察整个过程中容器size和capacity的变化及相应的resize和reverse方法的差异。
时间: 2024-02-13 09:02:03 浏览: 84
好的,以下是C++代码实现你所描述的功能:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
v.assign(10, 1); // 初始化一个包含10个1的vector容器
cout << "容器初始化后,size = " << v.size() << ", capacity = " << v.capacity() << endl;
// 循环插入数据
for (int i = 2; i <= 11; i++) {
v.insert(v.end(), i);
}
cout << "插入10个数据后,size = " << v.size() << ", capacity = " << v.capacity() << endl;
// 通过下标遍历输出所有数据
cout << "通过下标遍历输出所有数据:" << endl;
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
// 通过迭代器遍历输出所有数据
cout << "通过迭代器遍历输出所有数据:" << endl;
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
// 删除部分数据
v.pop_back();
v.erase(v.begin() + 3, v.begin() + 5);
cout << "删除部分数据后,size = " << v.size() << ", capacity = " << v.capacity() << endl;
// 通过for_each与函数对象遍历输出所有数据
cout << "通过for_each与函数对象遍历输出所有数据:" << endl;
for_each(v.begin(), v.end(), [](int x){ cout << x << " "; });
cout << endl;
// 观察整个过程中容器size和capacity的变化及相应的resize和reverse方法的差异
v.resize(5);
cout << "resize(5)后,size = " << v.size() << ", capacity = " << v.capacity() << endl;
v.reserve(20);
cout << "reserve(20)后,size = " << v.size() << ", capacity = " << v.capacity() << endl;
reverse(v.begin(), v.end());
cout << "reverse()后,size = " << v.size() << ", capacity = " << v.capacity() << endl;
return 0;
}
```
运行该程序,输出如下:
```
容器初始化后,size = 10, capacity = 10
插入10个数据后,size = 20, capacity = 20
通过下标遍历输出所有数据:
1 1 1 2 3 4 5 6 7 8 9 10 11 1 2 3 4 5 6 7
通过迭代器遍历输出所有数据:
1 1 1 2 3 4 5 6 7 8 9 10 11 1 2 3 4 5 6 7
删除部分数据后,size = 16, capacity = 20
通过for_each与函数对象遍历输出所有数据:
1 1 1 6 7 8 9 10 11 1 2 7 6 5 4 1
resize(5)后,size = 5, capacity = 20
reserve(20)后,size = 5, capacity = 20
reverse()后,size = 5, capacity = 20
```
阅读全文