C++ STL 中的 forward_list::swap()
c++server side programmingprogramming更新于 2025/4/23 16:52:17
给出的任务是展示 C++ 中 forward_list::swap() 函数的工作原理。
什么是前向列表?
前向列表是一个序列容器,允许在序列中的任何位置进行恒定时间插入和删除操作。前向列表作为单链表实现。顺序由每个元素与序列中下一个元素的链接关联来保持。
什么是forward_list::swap()?
forward_list::swap()是C++标准库函数中的一个函数,用于将一个列表的内容交换到另一个大小和数据类型相同的列表中。
语法
forward_list1.swap(forward_list2)
或
swap(forward_list first, forward_list second)
示例
输出 – 第一个列表:57 99 54 34 84 第二个列表:45 65 78 96 77 交换操作后输出为 第一个列表:45 65 78 96 77 第二个列表:57 99 54 34 84 输出 – 第一个列表:44 37 68 94 73 第二个列表:20 11 87 29 40 交换操作后输出为 第一个列表:20 11 87 29 40 第二个列表:44 37 68 94 73
可以遵循此方法
首先初始化两个前向列表。
然后我们打印两个前向列表。
然后我们定义 swap( ) 函数。
然后我们打印交换后的前向列表。
通过使用上述方法,我们可以交换两个前向列表。
算法
开始 −
步骤 1 – 初始化两个前向列表并打印它们 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 步骤 2 – 创建交换函数以执行交换操作。 swap( list1, list2) END 停止
示例
// C++ 代码演示 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<< “ List1 的元素:”; for( auto x = list1.start( ); x != list1.end( ); ++x ) cout<< *x << “ “ ; forward_list<int> list2 = { 40, 30, 20, 10, 50 } cout<< “List2 的元素:”; for( auto x = list2.start() ; x != list2.end() ; ++x ) cout<< *x << “ “ ; // 定义执行交换操作的函数 swap(list1, list2); cout<< “ 交换 List1 后为 :”; for(auto x = list1.start( ); x != list1.end( ); ++x) cout<< *x<< “ “; cout<< “ 交换 List2 后为 :”; for(auto x = list1.start( ); x!= list2.end( ); ++x) cout<< *x<< “ “; return 0; }
输出
如果我们运行上述代码,它将生成以下输出
输出 - List1 的元素:10 20 30 40 50 list2 的元素:40 30 20 10 50 交换 List1 后:40 30 20 10 50 交换list2 后:10 20 30 40 50 输出 - List1 的元素:23 56 78 49 11 list2 的元素:11 49 78 56 23 交换 List1 后:11 49 78 56 23 交换后 List1 :23 56 78 49 11