给出的任务是显示C ++中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( ){
//初始化两个转发列表
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 << “ “ ;
//定义执行交换操作的功能
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