功能描述:

    • 对list容器进行数据的插入和删除

    函数原型:

    • push_back(elem); //在容器尾部加入一个元素
    • pop_back(); //删除容器中最后一个元素
    • push_front(elem); //在容器开头插入一个元素
    • pop_front(); //从容器开头移除第一个元素
    • insert(pos,elem); //在pos位置插elem元素的拷贝,返回新数据的位置
    • insert(pos,n,elem); //在pos位置插入n个elem数据,无返回值
    • insert(pos,beg,end); //在pos位置插入[beg,end)区间的数据,无返回值
    • clear(); //移除容器中所有数据
    • erase(beg,end); //删除[beg,end)区间的数据,返回下一个数据的位置
    • erase(pos); //删除pos位置的数据,返回下一个数据的位置

    代码演示:

    1. #include<iostream>
    2. #include<list>
    3. using namespace std;
    4. //list容器插入和删除
    5. //● push_back(elem); //在容器尾部加入一个元素
    6. //● pop_back(); //删除容器中最后一个元素
    7. //● push_front(elem); //在容器开头插入一个元素
    8. //● pop_front(); //从容器开头移除第一个元素
    9. //● insert(pos, elem); //在pos位置插elem元素的拷贝,返回新数据的位置
    10. //● insert(pos, n, elem); //在pos位置插入n个elem数据,无返回值
    11. //● insert(pos, beg, end); //在pos位置插入[beg,end)区间的数据,无返回值
    12. //● clear(); //移除容器中所有数据
    13. //● erase(beg, end); //删除[beg,end)区间的数据,返回下一个数据的位置
    14. //● erase(pos); //删除pos位置的数据,返回下一个数据的位置
    15. void printList(const list<int>& L) {
    16. for (list<int>::const_iterator it = L.begin(); it != L.end(); it++) {
    17. cout << *it << " ";
    18. }
    19. cout << endl;
    20. }
    21. //赋值
    22. void test01() {
    23. //创建list容器
    24. list<int>L1;//默认构造
    25. //尾插
    26. L1.push_back(10);
    27. L1.push_back(20);
    28. L1.push_back(30);
    29. //头插
    30. L1.push_front(1);
    31. L1.push_front(2);
    32. L1.push_front(3);
    33. //遍历容器
    34. printList(L1);//3 2 1 10 20 30
    35. //尾删
    36. L1.pop_back();
    37. printList(L1);//3 2 1 10 20
    38. //头删
    39. L1.pop_front();
    40. printList(L1);//2 1 10 20
    41. //insert插入
    42. list<int>::iterator it = L1.begin();
    43. L1.insert(++it , 3);//list无法跳跃移动,只能++
    44. //L1.insert(it + 1, 3);//错的
    45. //L1.insert(++L1.begin(), 3); //对的
    46. printList(L1);//2 3 1 10 20
    47. //删除
    48. it = L1.begin();
    49. L1.erase(++it);
    50. printList(L1);//2 1 10 20
    51. L1.push_back(10);
    52. //匹配移除
    53. cout << "移除前:";
    54. L1.push_back(10);
    55. printList(L1);//2 1 10 20 10
    56. L1.remove(10);
    57. cout << "移除后:";
    58. printList(L1);//2 1 20
    59. //清空
    60. L1.clear();
    61. printList(L1);
    62. }
    63. int main() {
    64. test01();
    65. return 0;
    66. }

    运行结果:
    image.png