21xrx.com
2024-09-20 06:00:29 Friday
登录
文章检索 我的文章 写文章
C++11 STL List 交换(Swap)
2023-06-26 07:26:14 深夜i     --     --
C++11 STL List 交换 Swap

在使用C++11 STL List时,交换操作是一个非常重要的操作。它允许我们将两个List中的元素进行交换,这样就可以改变它们在List中的相对位置。

在C++11中,我们可以使用自带的swap函数来交换两个List的元素。这个函数是定义在 库中的,需要包含头文件进行调用。

下面是一个例子,演示了如何使用C++11 STL List的swap函数:


#include <iostream>

#include <list>

#include <algorithm>

using namespace std;

int main() {

  list<int> list11;

  list<int> list2 5;

  cout << "list1 before swap:";

  for (int i : list1)

    cout << " " << i;

  

  cout << endl;

  cout << "list2 before swap:";

  for (int i : list2)

    cout << " " << i;

  

  cout << endl;

  swap(list1, list2);

  cout << "list1 after swap:";

  for (int i : list1)

    cout << " " << i;

  

  cout << endl;

  cout << "list2 after swap:";

  for (int i : list2)

    cout << " " << i;

  

  cout << endl;

  return 0;

}

输出结果为:


list1 before swap: 1 2 3

list2 before swap: 4 5 6

list1 after swap: 4 5 6

list2 after swap: 1 2 3

从输出结果可以看出,swap函数可以非常方便地交换两个List中的元素。需要注意的是,这个函数还可以将任何类型的STL容器进行交换操作。

总之,在使用C++11 STL List时,swap函数是一个非常实用和方便的工具。它可以帮助我们快速地改变List中元素的相对位置,从而满足我们的具体需求。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复