C++ STL 中的 list swap( )


以下是展示 C++ 中 STL 中 list swap( ) 函式功能的任務。

什麼是 STL 中的 list?

List 是允許在序列中的任何位置進行恆定時間插入和刪除的容器。List 被實現為雙向連結串列。List 允許非連續記憶體分配。與陣列、vector 和 deque 相比,list 在容器中的任何位置都能更好地執行元素的插入、提取和移動。在 list 中,直接訪問元素很慢,list 類似於 forward_list,但 forward list 物件是單鏈表,並且只能正向迭代。

什麼是 swap( )?

此函式用於將一個 list 的元素與另一個 list 的元素進行交換,且兩者擁有相同的資料型別和大小。

語法:listname1.swap(listname2)

示例

Input List1: 50 60 80 90
List2: 90 80 70 60

Output After swapping operation
List1: 90 80 70 60
List2: 50 60 80 90
Input List1: 45 46 47 48 49
List2: 50 51 52 53 54

Output After swapping Operation
List1: 50 51 52 53 54
List2: 45 46 47 48 49

可以採用以下方法

  • 首先,我們初始化兩個 list。

  • 然後,我們列印這兩個 list。

  • 然後,我們定義 swap( ) 函式。

  • 最後,我們在執行交換操作後列印兩個 list。

透過使用上述方法,我們可以交換兩個 list。

示例

// C++ code to demonstrate the working of list swap( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
int main ( ){
   // initializing two lists
   List<int> list1 = { 10, 20, 30, 40, 50 };
   cout<< “ List1: “;
   for( auto x = list1.begin( ); x != list1.end( ); ++x)
      cout<< *x << “ “;
   List<int> list2 = { 40, 50, 60, 70, 80 };
   cout<< “ List2: “;
   for( auto x = list2.begin( ); x != list2.end( ); ++x)
   cout<< *x << “ “;
   // defining swap( ) function
   list1.swap(list2);
   cout<< “ After swapping List1 is :”;
   for(auto x = list1.begin( ); x != list1.end( ); ++x)
      cout<< *x<< “ “;
   cout<< “ After swapping List2 is :”;
   for(auto x = list1.begin( ); x!= list2.end( ); ++x)
      cout<< *x<< “ “;
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出

Input - List1: 10 20 30 40 50
List2: 40 50 60 70 80

Output - After swapping List1 is: 40 50 60 70 80
After swapping List2 is: 10 20 30 40 50

示例

// C++ code to demonstrate the working of list swap( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
int main ( ){
   // initializing two lists
   list<int> list1 = { 11, 12, 13, 14, 15 };
   cout<< “ List1: “;
   for( auto x = list1.begin( ); x != list1.end( ); ++x)
      cout<< *x << “ “;
   List<int> list2 = { 16, 17, 18, 19, 20 };
   cout<< “ List2: “;
   for( auto x = list2.begin( ); x != list2.end( ); ++x)
      cout<< *x << “ “;
   // defining swap( ) function
   list1.swap(list2);
   cout<< “ After swapping List1 is :”;
   for(auto x = list1.begin( ); x != list1.end( ); ++x)
   cout<< *x<< “ “;
   cout<< “ After swapping List2 is :”;
   for(auto x = list1.begin( ); x!= list2.end( ); ++x)
      cout<< *x<< “ “;
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出

Input - List1: 11 12 13 14 15
   List2: 16 17 18 19 20
Output - After swapping List1 is: 16 17 18 19 20
   After swapping List2 is: 11 12 13 14 15

更新於: 2020-03-05

488 次瀏覽

開啟您的職業生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.