学习链接
插入元素
vector.insert(pos,elem); //在pos位置插入一个elem元素的拷贝,返回新数据的位置。
vector.insert(pos,n,elem); //在pos位置插入n个elem数据,无返回值。
vector.insert(pos,beg,end); //在pos位置插入[beg,end)区间的数据,无返回值 。
删除元素
vector.clear(); //移除容器的所有数据
vec.erase(beg,end); //删除[beg,end)区间的数据,返回下一个数据的位置。
vec.erase(pos); //删除pos位置的数据,返回下一个数据的位置。
#include#include using namespace std; //输出函数 void co(string &a,vector &x){ for(auto i : a){ cout< a; vector b; for(int i = 0; i < 5; i++){ a.push_back(i); } b.push_back(100); b.push_back(200); b.push_back(300); string tag = "a"; co(tag,a); tag = "b"; co(tag,b); int n; a.insert(a.begin() + 2,600); tag = "a1"; co(tag,a); for(int i = 0; i < a.size(); i++){ cout<<"当前a大小为:"< ::iterator it = a.erase(a.begin()+1); tag = "a3"; co(tag,a); //测试迭代器是否指向下一个元素 a.insert(it,2); tag = "a4"; co(tag,a); a.erase(a.begin()+0,a.begin()+2); tag = "a5"; co(tag,a); }
输入结果:
/home/rock/CLionProjects/untitled/cmake-build-debug/untitled a: [ 0 1 2 3 4 ] b: [ 100 200 300 ] a1: [ 0 1 600 2 3 4 ] 当前a大小为:6 当前a大小为:5 当前a大小为:4 a2: [ 1 2 4 ] a3: [ 1 4 ] a4: [ 1 2 4 ] a5: [ 4 ] Process finished with exit code 0



