C++ STL中的unordered_multiset swap()
“unordered_multiset”的swap()方法交换两个容器的内容。它是公共成员函数。这个函数:
- 通过另一个 unordered_multiset 对象的内容与容器的内容进行交换,该对象包含相同类型的元素,但大小可能不同。
- 此成员函数调用后,此容器中的元素是在调用前在对象中的元素,并且变量中的元素是在这个容器中的元素。
语法:
void swap(unordered_multiset &another_unordered_multiset);
参数:它接收与此容器相同类型的另一个unordered_multiset容器对象进行交换。
返回值:它不返回任何值。
下面的程序演示unordered_multiset swap()函数:
Example 1:
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
int main()
{
// sets the values in two container
unordered_multiset<string>
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
Example 2:
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
int main()
{
// sets the values in two container
unordered_multiset<int>
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