forward_list::swap() 在 C++ STL 中
給出了在 C++ 中展示 forward_list::swap() 函式的工作原理的任務。
什麼是前向列表?
前向列表是一個順序容器,允許在序列中的任何位置進行恆定時間的插入和刪除操作。前向列表作為單鏈表實現。順序是透過將每個元素與序列中下一個元素的連結關聯來保持的。
什麼是 forward_list::swap()?
forward_list::swap() 是 c++ 標準庫函式中用於將一個列表的內容交換到另一個大小相同且資料型別相同列表的函式。
語法
forward_list1.swap(forward_list2)
或
swap(forward_list first, forward_list second)
示例
Output – First list : 57 99 54 34 84 Second list : 45 65 78 96 77 After swapping operation outputs are First list : 45 65 78 96 77 Second list : 57 99 54 34 84 Output – First list : 44 37 68 94 73 Second list : 20 11 87 29 40 After swapping operation outputs are First list : 20 11 87 29 40 Second list : 44 37 68 94 73
可以遵循的方法
首先初始化兩個正向列表。
然後我們列印兩個向前列表內容。
然後我們定義 swap() 函式。
然後我們列印交換後的正向列表內容。
使用上述方法,我們可以交換兩個前向列表。
演算法
開始 -
STEP 1 – Intialize the two forward list and print them
First list forward_list<int> List1 = { 10, 20, 30, 40, 50 }
for( auto x = list1.start( ); x != list1.end( ); ++x )
cout<< *x << “ “ ;
second list forward_list<in> list2 = { 40, 30, 20, 10, 50 }
for( auto x = list2.start( ); x != list2.end( ); ++x )
cout<< *x << “ “ ;
END
STEP 2 – create the swap function to perform swap operation.
swap( list1, list2)
END
Stop示例
// C++ code to demonstrate the working of forward_list::reverse( )
#include<iostream.h>
#include<forward_list.h>
Using namespace std;
Int main( ){
// initializing two forward lists
forward_list<int> list1 = { 10, 20, 30, 40, 50 }
cout<< “ Elements of List1:”;
for( auto x = list1.start( ); x != list1.end( ); ++x )
cout<< *x << “ “ ;
forward_list<int> list2 = { 40, 30, 20, 10, 50 }
cout<< “Elements of List2:”;
for( auto x = list2.start( ); x != list2.end( ); ++x )
cout<< *x << “ “ ;
// defining of function that performs the swap operation
swap(list1, list2);
cout<< “ After swapping List1 is :”;
for(auto x = list1.start( ); x != list1.end( ); ++x)
cout<< *x<< “ “;
cout<< “ After swapping List2 is :”;
for(auto x = list1.start( ); x!= list2.end( ); ++x)
cout<< *x<< “ “;
return 0;
}輸出
如果我們執行上述程式碼,它將生成以下輸出
OUTPUT – Elements of List1 : 10 20 30 40 50 Elements of list2 : 40 30 20 10 50 After Swapping List1 : 40 30 20 10 50 After Swapping List2 : 10 20 30 40 50 OUTPUT – Elements of List1 : 23 56 78 49 11 Elements of List2 : 11 49 78 56 23 After Swapping List1 : 11 49 78 56 23 After Swapping List1 : 23 56 78 49 11
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP