“ unordered_set”的swap()方法交换两个容器的内容。它是公共成员函数。该函数:
- 通过变量content交换容器的内容,变量是另一个unordered_set对象,其中包含相同类型的元素,但大小可能有所不同。
- 该呼叫到该成员函数之后,在该容器中的元素是那些均可变呼叫之前,和可变的元素是那些被在此。
句法:
void swap(unordered_set &another_unordered_set);
参数:它接收与该容器要交换的容器类型相同的another_unordered_set容器对象。
返回值:不返回任何值。
下面的程序说明了unordered_set swap()函数:-
范例1:
#include
#include
#include
using namespace std;
int main()
{
// sets the values in two container
unordered_set
first = { "FOR GEEKS" },
second = { "GEEKS" };
// before swap values
cout << "before swap :- \n";
cout << "1st container : ";
for (const string& x : first)
cout << x << endl;
cout << "2nd container : ";
for (const string& x : second)
cout << x << endl;
// call swap
first.swap(second);
// after swap values
cout << "\nafter swap :- \n";
// displaying 1st container
cout << "1st container : ";
for (const string& x : first)
cout << x << endl;
// displaying 2nd container
cout << "2nd container : ";
for (const string& x : second)
cout << x << endl;
return 0;
}
输出:
before swap :-
1st container : FOR GEEKS
2nd container : GEEKS
after swap :-
1st container : GEEKS
2nd container : FOR GEEKS
范例2:
#include
#include
#include
using namespace std;
int main()
{
// sets the values in two container
unordered_set
first = { 1, 2, 3 },
second = { 4, 5, 6 };
// before swap values
cout << "before swap :- \n";
cout << "1st container : ";
for (const int& x : first)
cout << x << " ";
cout << endl;
cout << "2nd container : ";
for (const int& x : second)
cout << x << " ";
cout << endl;
// call swap
first.swap(second);
// after swap values
cout << "\nafter swap :- \n";
// displaying 1st container
cout << "1st container : ";
for (const int& x : first)
cout << x << " ";
cout << endl;
// displaying 2nd container
cout << "2nd container : ";
for (const int& x : second)
cout << x << " ";
cout << endl;
return 0;
}
输出:
before swap :-
1st container : 3 2 1
2nd container : 6 5 4
after swap :-
1st container : 6 5 4
2nd container : 3 2 1
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。