當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Forward_list swap()用法及代碼示例


描述

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

聲明

以下是 std::forward_list::swap() 函數形式 std::forward_list 頭文件的聲明。

C++11

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

參數

  • first− 第一個 forward_list 對象。

  • second− 第二個 forward_list 對象。

返回值

異常

此函數從不拋出異常。

時間複雜度

線性,即 O(n)

示例

下麵的例子展示了 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;

   swap(fl1, 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

相關用法


注:本文由純淨天空篩選整理自 C++ Forward_list Library - swap() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。