功能描述:

    • 互换两个容器的元素

    函数原型:

    • swap(container c1, container c2);

    //互换两个容器的元素
    //c1容器1
    //c2容器2

    代码演示:

    1. #include<iostream>
    2. #include<algorithm>
    3. #include<vector>
    4. using namespace std;
    5. //常用拷贝和替换算法 swap
    6. class myprint {
    7. public:
    8. void operator()(int val) {
    9. cout << val << " ";
    10. }
    11. };
    12. void test01() {
    13. vector<int>v1;
    14. vector<int>v2;
    15. for (int i = 1; i <= 10; i++) {
    16. v1.push_back(i);
    17. v2.push_back(i + 10);
    18. }
    19. cout << "交换前:" << endl;
    20. for_each(v1.begin(), v1.end(),myprint());
    21. cout << endl;
    22. for_each(v2.begin(), v2.end(),myprint());
    23. cout << endl;
    24. cout << endl;
    25. cout << "交换后:" << endl;
    26. swap(v1, v2);
    27. for_each(v1.begin(), v1.end(), myprint());
    28. cout << endl;
    29. for_each(v2.begin(), v2.end(), myprint());
    30. cout << endl;
    31. }
    32. int main() {
    33. test01();
    34. return 0;
    35. }

    运行结果:
    image.png