功能描述:

    • 给list容器进行赋值,以及交换list容器

    函数原型:

    • assign(beg,end); //将[beg,end)区间中的数据拷贝赋值给本身。
    • assign(n,elem); //将n个elem拷贝赋值给本身
    • list& operator=(const list &lst); //重载等号操作符
    • swap(lst); //将lst与本身的元素互换

    源码展示:

    1. #include<iostream>
    2. #include<list>
    3. using namespace std;
    4. //list容器的赋值和交换
    5. void printList(const list<int>& L) {
    6. for (list<int>::const_iterator it = L.begin(); it != L.end(); it++) {
    7. cout << *it << " ";
    8. }
    9. cout << endl;
    10. }
    11. //赋值
    12. void test01() {
    13. //创建list容器
    14. list<int>L1;//默认构造
    15. //添加数据
    16. L1.push_back(10);
    17. L1.push_back(20);
    18. L1.push_back(30);
    19. L1.push_back(40);
    20. //遍历容器
    21. printList(L1);
    22. list<int>L2;
    23. L2 = L1;//operator = 赋值
    24. printList(L2);
    25. list<int>L3;
    26. L3.assign(L1.begin(), L1.end());//区间赋值
    27. printList(L3);
    28. list<int>L4;
    29. L4.assign(10,1000);//区间赋值
    30. printList(L4);
    31. }
    32. //交换
    33. void test02() {
    34. //创建list容器
    35. list<int>L1;//默认构造
    36. //添加数据
    37. L1.push_back(10);
    38. L1.push_back(20);
    39. L1.push_back(30);
    40. L1.push_back(40);
    41. list<int>L2;
    42. L2.assign(10, 1000);//区间赋值
    43. cout << "交换前:" << endl;
    44. printList(L1);
    45. printList(L2);
    46. L1.swap(L2);
    47. cout << "交换后:" << endl;
    48. printList(L1);
    49. printList(L2);
    50. }
    51. int main() {
    52. test01();
    53. test02();
    54. return 0;
    55. }

    运行结果:
    image.png