在C ++ STL中列出swap()

2023年11月18日08:56:36

给出的任务是显示STL中C ++中的功能列表swap()函数。

什么是STL中的列表?

列表是允许在任何地方按顺序进行恒定时间插入和删除的容器。列表被实现为双链表。列表允许不连续的内存分配。与数组,向量和双端队列相比,列表在容器中的任何位置执行元素的插入提取和移动效果更好。在列表中,直接访问该元素的速度很慢,并且列表类似于forward_list,但是转发列表对象是单个链接列表,并且只能迭代转发。

什么是swap()?

此函数用于将一个列表的元素与另一列表交换,并且两者具有相同的数据类型和大小。

语法: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。

  • 然后我们打印两个列表。

  • 然后我们定义swap()函数。

  • 最后,我们在交换操作后打印了两个列表。

通过使用上述方法,我们可以交换两个列表。

示例

// C++ code to demonstrate the working of list swap( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
int main ( ){
   //初始化两个列表
   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 << “ “;
   //定义swap()函数
   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 ( ){
   //初始化两个列表
   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 << “ “;
   //定义swap()函数
   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

  • 更新时间:2023年11月18日08:56:36 ,共 2359 字。