//用于演示向量
中的擦除功能的C ++代码#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v1(1, 2); // default constructor to assign one element
vector<int>::iterator it = v1.begin();
cout << "v1 initially contains : ";
for (int i = 0; i < v1.size(); ++i)
cout << v1[i] << '\t';
cout << endl;
v1.insert(it + 1, 3, 5); //inserting 3 elements of value 5
cout << "v1 now contains : ";
for (int i = 0; i < v1.size(); ++i)
cout << v1[i] << '\t';
cout << endl;
v1.erase(it + 2, it + 4); // erasing elements in the range
cout << "v1 now contains : ";
for (int i = 0; i < v1.size(); ++i)
cout << v1[i] << '\t';
cout << endl;
return 0;
}
此代码正在创建一个向量并为其指定值2。然后使用迭代器将其打印出来。接下来,我们在向量中插入3个元素,每个元素都是5.然后使用迭代器我试图删除(它+2和它+4)之间的元素。然后在尝试打印最终矢量时,我不确定为什么要打印5 5。