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
廣告

© . All rights reserved.