C++ 列表库 - swap() 函数



描述

C++ 函数std::list::swap()交换第一个列表与另一个列表的内容。如果需要,此函数会更改列表的大小。

声明

以下是来自 std::list 头文件的 std::list::swap() 函数的声明。

C++98

template <class T, class Alloc>
void swap (list<T,Alloc>& first, list<T,Alloc>& second);

参数

  • first - 第一个列表对象。

  • second - 第二个列表对象。

返回值

无。

异常

此函数从不抛出异常。

时间复杂度

线性,即 O(n)

示例

以下示例显示了 std::list::swap() 函数的使用方法。

#include <iostream>
#include <list>

using namespace std;

int main(void) {
   list<int> l1 = {1, 2, 3};
   list<int> l2 = {10, 20, 30, 40, 50};

   cout << "List l1 contains following elements before swap operation" << endl;
   for (auto it = l1.begin(); it != l1.end(); ++it)
      cout << *it << endl;

   cout << "List l2 contains following elements before swap operation" << endl;
   for (auto it = l2.begin(); it != l2.end(); ++it)
      cout << *it << endl;

   swap(l1, l2);

   cout << "List l1 contains following elements after swap operation" << endl;
   for (auto it = l1.begin(); it != l1.end(); ++it)
      cout << *it << endl;

   cout << "List l2 contains following elements after swap operation" << endl;
   for (auto it = l2.begin(); it != l2.end(); ++it)
      cout << *it << endl;

   return 0;
}

让我们编译并运行上述程序,这将产生以下结果:

List l1 contains following elements before swap operation
1
2
3
List l2 contains following elements before swap operation
10
20
30
40
50
List l1 contains following elements after swap operation
10
20
30
40
50
List l2 contains following elements after swap operation
1
2
3
list.htm
广告