vector容器的插入和删除(5)
功能描述:
- 对vector容器进行插入、删除操作
函数原型:
push_back(ele);
//尾部插入元素ele
pop_back();
//删除最后一个元素
insert(const_iterator pos, ele);
//迭代器指向位置pos插入元素ele
insert(const_iterator pos, int count,ele);
//迭代器指向位置pos插入count个元素ele
erase(const_iterator pos);
//删除迭代器指向的元素
erase(const_iterator start, const_iterator end);
//删除迭代器从start到end之间的元素
clear();
//删除容器中所有元素
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 5 void printVector(vector<int> &v) 6 { 7 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 8 { 9 cout << *it << " "; 10 } 11 cout << endl; 12 } 13 14 15 void test_01() 16 { 17 vector<int> v1; 18 //尾插 19 v1.push_back(10); 20 v1.push_back(20); 21 v1.push_back(30); 22 v1.push_back(40); 23 v1.push_back(50); 24 printVector(v1); 25 26 //尾删 27 v1.pop_back(); 28 printVector(v1); 29 30 //插入 31 v1.insert(v1.begin(), 100); 32 printVector(v1); 33 34 v1.insert(v1.begin(), 2, 1000); 35 printVector(v1); 36 37 //删除 38 v1.erase(v1.begin()); 39 printVector(v1); 40 41 v1.erase(v1.begin(), v1.end()); 42 printVector(v1); 43 44 //清空 45 v1.clear(); 46 printVector(v1); 47 48 } 49 50 int main(void) 51 { 52 test_01(); 53 54 system("pause"); 55 return 0; 56 57 }