46 lines
1017 B
C++
46 lines
1017 B
C++
|
|
// vector 的删除操作
|
|
#include <bits/stdc++.h>
|
|
|
|
using namespace std;
|
|
|
|
template <typename T>
|
|
void print(vector<T> &v)
|
|
{
|
|
typename vector<T>::iterator it = v.begin();
|
|
while (it != v.end())
|
|
{
|
|
cout << *it << " ";
|
|
it++;
|
|
}
|
|
cout << endl;
|
|
}
|
|
|
|
int main()
|
|
{
|
|
int arr1[5] = {1, 2, 3, 4, 5};
|
|
vector<int> v1(arr1, arr1 + 5);
|
|
print(v1);
|
|
|
|
vector<int>::iterator it = v1.begin();
|
|
v1.insert(it, 1, 10); // 在 it 位置插入 1 个 10
|
|
print(v1);
|
|
|
|
it = v1.begin(); // 重新获取迭代器,因为之前的迭代器已经失效(插入后迭代器首地址变了)
|
|
v1.erase(it); // 删除 it 位置的元素
|
|
print(v1);
|
|
|
|
it = v1.begin();
|
|
v1.erase(it, it + 2); // 删除 [it, it+2) 位置的元素
|
|
print(v1);
|
|
|
|
// 清空
|
|
v1.clear();
|
|
v1.empty(); // 判断是否为空
|
|
cout << "清空后:" << endl;
|
|
print(v1);
|
|
cout << "size: " << v1.size() << " capacity: " << v1.capacity() << endl; // size: 0 capacity: 8
|
|
|
|
return 0;
|
|
}
|