分享

容器中swap成员函数

 兰亭文艺 2019-01-28
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函数的理解,如下图所示:

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多