c++容器中swap函数用法

 转载自:https://blog.csdn.net/yang20141109/article/details/50759461

swap操作交换两个相同类型容器中的内容,调用swap函数后,两个容器中的元素将会交换,容器中的元素交换以后会对容器的迭代器、引用、和指针有什么影响。
    第一种情况:如果容器是vector,list等容器,交换两个容器的内容的操作保证会很快,因为元素本身并不交换,swap只是交换了两个容器的内部数据结构。其指向容器的迭代器、引用和指针在swap操作之后都不会失效。他们仍然指向swap操作之前所指向的元素。但是,在swap操作之后,这些元素已经属于不同的容器了。例如如下代码:假定iter在交换之前指向ve1[3]中的元素,那么在swap之后它指向的是ve2[3]中的元素。
vector<int> ve1(10);
vector<int> ve2(20);
ve1.swap(ve2);
总代码如下:
#include<iostream>
#include<memory>
#include<vector>
#include<array>
#include<string>
#include<list>
using namespace std;
 
int main(void)
{
    vector<int> ve1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    vector<int> ve2 = { 11, 12, 13, 14, 15 };
    auto it1 = ve1.begin();
    auto it2 = ve2.begin();
    cout << "交换之前,*it1 = " << *it1 << endl;
    cout << "交换之前,*it2 = " << *it2 << endl;
    swap(ve1, ve2);
    cout << "交换之后,*it1 = " << *it1 << endl;
    cout << "交换之后,*it2 = " << *it2 << endl;
    auto end = ve2.end();
    while (it1 != end)
    {
        cout << *it1++ << endl;
    }
    system("pause");
    return 0;
}
第二种情况:如果容器是array类型,swap操作会真正交换它们中的元素,因此,交换两个array所需要的时间与array中元素的数目成正比。但是,在swap操作之后,指针、迭代器和引用所绑定的元素不变,但是其值已经是另一个array中的对应元素的值。例如如下代码:假定iter在交换之前指向的是arr1[0]=1,则交换操作以后,iter仍然指向的是arr1[0]中的元素,不过此时arr1[0]=6。
array<int,5> arr1 = {1, 2, 3, 4, 5};
array<int,5> arr2 = {6, 7, 8, 9, 10};
arr1.swap(arr2);
总代码如下:
#include<iostream>
#include<memory>
#include<vector>
#include<array>
#include<string>
#include<list>
using namespace std;
 
int main(void)
{
    array<int, 10> ve1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    array<int, 10> ve2 = { 11, 12, 13, 14, 15 };
    auto it1 = ve1.begin();
    auto it2 = ve2.begin();
    cout << "交换之前,*it1 = " << *it1 << endl;
    cout << "交换之前,*it2 = " << *it2 << endl;
    ve1.swap(ve2);
    cout << "交换之后,*it1 = " << *it1 << endl;
    cout << "交换之后,*it2 = " << *it2 << endl;
    auto end = ve1.end();
    while (it1 != end)
    {
        cout << *it1++ << endl;
    }
    system("pause");
    return 0;
}
下面是本人对swap函数的理解,如下图所示:
--------------------- 
作者:yang20141109 
来源:CSDN 
原文:https://blog.csdn.net/yang20141109/article/details/50759461 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值