C++ forward_list 庫 - swap() 函式



描述

C++ 函式std::forward_list::swap() 交換第一個 forward_list 與另一個 forward_list 的內容。如果需要,此函式會更改 forward_list 的大小。

宣告

以下是來自 std::forward_list 標頭檔案的 std::forward_list::swap() 函式的宣告。

C++11

void swap (forward_list& other);

引數

other - 另一個相同型別的 forward_list 物件。

返回值

異常

此成員函式永遠不會丟擲異常。

時間複雜度

常數,即 O(1)

示例

以下示例顯示了 std::forward_list::swap() 函式的使用方法。

#include <iostream>
#include <forward_list>

using namespace std;

int main(void) {

   forward_list<int> fl1 = {1, 2, 3, 4, 5};;
   forward_list<int> fl2 = {10, 20, 30};

   cout << "List fl1 contents before swap operation" << endl;

   for (auto it = fl1.begin(); it != fl1.end(); ++it)
      cout << *it << endl;

   cout << "List fl2 contents before swap operation" << endl;

   for (auto it = fl2.begin(); it != fl2.end(); ++it)
      cout << *it << endl;

   fl1.swap(fl2);

   cout << endl;

   cout << "List fl1 contents after swap operation" << endl;

   for (auto it = fl1.begin(); it != fl1.end(); ++it)
      cout << *it << endl;

   cout << "List fl2 contents after swap operation" << endl;

   for (auto it = fl2.begin(); it != fl2.end(); ++it)
      cout << *it << endl;
   return 0;
}

讓我們編譯並執行以上程式,這將產生以下結果:

List fl1 contents before swap operation
1
2
3
4
5
List fl2 contents before swap operation
10
20
30

List fl1 contents after swap operation
10
20
30
List fl2 contents after swap operation
1
2
3
4
5
forward_list.htm
廣告

© . All rights reserved.