vector<int> num; for (int i=0; i<10; ++i)num.push_back(i); num.push_back(10); num.push_back(10); cout << "Original array:\n"; //vector<int>::iterator it; //C++11之前用的,11之后可以用auto for (auto it=num.begin(); it!=num.end(); ++it) { cout << *it << " "; } cout << endl; num.insert(num.begin()+2,3,10); //在num[2]之前加3个10 cout << "Inserted array:\n"; for (auto it=num.begin(); it!=num.end(); ++it) { cout << *it << " "; } cout << endl; //delete 10 for (auto it=num.begin(); it!=num.end(); ++it) { if ( *it == 10 ) { num.erase(it); //删除it指向的元素,后it自动指向下一个元素 --it; } } cout << "Deleted 10 array:\n"; for (auto it=num.begin(); it!=num.end(); ++it) { cout << *it << " "; }
运行结果:
原文地址:https://www.cnblogs.com/htj10/p/9194776.html
时间: 2024-10-11 08:47:14