forward_list :: swap()是CPP STL中的内置函数,它将第一个给定的forward_list的内容与另一个forward_list交换。
句法:
swap(forward_list first, forward_list second)
or
forward_list1.swap(forward_list second)
参数:该函数接受两个指定如下的参数:
- 第一–第一个forward_list
- 第二–第二个forward_list
返回值:该函数不返回任何内容。它交换两个列表。
下面的程序演示了上述函数:
程序1:
// CPP program that demonstrates the
// forward_list::swap() function
// when two parameters is passed
#include
using namespace std;
int main()
{
// initialising the two forward_list
forward_list firstlist = { 9, 8, 7, 6 };
forward_list secondlist = { 10, 20, 30 };
// printing elements before the swap operation
// for firstlist and secondlist
cout << "Before swap operation firstlist was: ";
for (auto it = firstlist.begin(); it != firstlist.end(); ++it)
cout << *it << " ";
cout << "\nBefore swap operation secondlist was: ";
for (auto it = secondlist.begin(); it != secondlist.end(); ++it)
cout << *it << " ";
// swap operation on two lists
swap(firstlist, secondlist);
// printing elements after the swap operation
// for forward1 and secondlist
cout << "\n\nAfter swap operation firstlist is: ";
for (auto it = firstlist.begin(); it != firstlist.end(); ++it)
cout << *it << " ";
cout << "\nAfter swap operation secondlist is:";
for (auto it = secondlist.begin(); it != secondlist.end(); ++it)
cout << *it << " ";
return 0;
}
输出:
Before swap operation firstlist was: 9 8 7 6
Before swap operation secondlist was: 10 20 30
After swap operation firstlist is: 10 20 30
After swap operation secondlist is:9 8 7 6
程式2:
// CPP program that demonstrates the
// forward_list::swap() function
// when two parameters is passed
#include
using namespace std;
int main()
{
// initialising the two forward_list
forward_list firstlist = { 9, 8, 7, 6 };
forward_list secondlist = { 10, 20, 30 };
// printing elements before the swap operation
// for firstlist and secondlist
cout << "Before swap operation firstlist was: ";
for (auto it = firstlist.begin(); it != firstlist.end(); ++it)
cout << *it << " ";
cout << "\nBefore swap operation secondlist was: ";
for (auto it = secondlist.begin(); it != secondlist.end(); ++it)
cout << *it << " ";
// swap operation on two lists
firstlist.swap(secondlist);
// printing elements after the swap operation
// for forward1 and secondlist
cout << "\n\nAfter swap operation firstlist is: ";
for (auto it = firstlist.begin(); it != firstlist.end(); ++it)
cout << *it << " ";
cout << "\nAfter swap operation secondlist is:";
for (auto it = secondlist.begin(); it != secondlist.end(); ++it)
cout << *it << " ";
return 0;
}
输出:
Before swap operation firstlist was: 9 8 7 6
Before swap operation secondlist was: 10 20 30
After swap operation firstlist is: 10 20 30
After swap operation secondlist is:9 8 7 6
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。