unordered_multiset::swap()是C++ STL中的内置函数,该函数交换两个unordered_multiset的内容
容器。
注意:两个容器应具有相同类型的元素。容器的尺寸可能会有所不同。
用法:
unordered_multiset1.swap(unordered_multiset2);
参数:该函数仅接受一个强制参数,即unordered_multiset2,通过该参数可以进行unordered_multiset1的交换。
返回值:它不返回任何值。
以下示例程序旨在说明上述函数。
示例1:
// C++ program to illustrate
// unordered_multiset::swap()
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
// Function to display the contents of multiset s.
void display(unordered_multiset<int> s)
{
for (auto it = s.begin(); it != s.end(); it++)
cout << *it<<" ";
cout<<"\n";
}
int main()
{
// Declaration
unordered_multiset<int> s1, s2;
// initializing both multisets(sizes are different)
s1 = { 1, 2, 3, 4 };
s2 = { 10, 20, 30, 40, 50 };
// diplaying initial values
cout << "Initial values of s1 are: \n";
display(s1);
cout << endl;
cout << "Initial values of s2 are: \n";
display(s2);
cout << endl;
// swapping the values
s1.swap(s2);
// display final values
cout << "Final values of s1 are: \n";
display(s1);
cout << endl;
cout << "Final values of s2 are: \n";
display(s2);
return 0;
}
输出:
Initial values of s1 are: 4 3 2 1 Initial values of s2 are: 50 40 30 20 10 Final values of s1 are: 50 40 30 20 10 Final values of s2 are: 4 3 2 1
示例2:
// C++ program to illustrate
// unordered_multiset::swap()
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
// Function to display the contents of multiset s
void display(unordered_multiset<string> s)
{
for (auto it = s.begin(); it != s.end(); it++)
cout << *it << " ";
cout<<endl;
}
int main()
{
// Declaration
unordered_multiset<string> s1, s2;
// Initializing both multisets(sizes are different)
s1 = { "Geeks", "for", "Geeks" };
s2 = { "Computer", "Science", "Portal", "for", "Geeks" };
// Diplaying initial values
cout << "Initial values of s1 are: \n";
display(s1);
cout << endl;
cout << "Initial values of s2 are: \n";
display(s2);
cout << endl;
// Swapping
s1.swap(s2);
// Display final values
cout << "Final values of s1 are: \n";
display(s1);
cout << endl;
cout << "Final values of s2 are: \n";
display(s2);
return 0;
}
输出:
Initial values of s1 are: for Geeks Geeks Initial values of s2 are: Geeks for Portal Science Computer Final values of s1 are: Geeks for Portal Science Computer Final values of s2 are: for Geeks Geeks
相关用法
- C++ valarray swap()用法及代码示例
- C++ unordered_set swap()用法及代码示例
- C++ unordered_multimap swap()用法及代码示例
- C++ multimap swap()用法及代码示例
- C++ set::swap()用法及代码示例
- C++ map::at()、map::swap()用法及代码示例
- C++ swap()用法及代码示例
- C++ list::swap()用法及代码示例
- C++ queue::swap()用法及代码示例
- C++ priority_queue::swap()用法及代码示例
- C++ forward_list::swap()用法及代码示例
- C++ multimap::swap()用法及代码示例
- C++ unordered_multiset swap()用法及代码示例
注:本文由纯净天空筛选整理自Kushagra7744大神的英文原创作品 unordered_multiset swap() function in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。