代码

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

运行结果

image.png