unordered_multiset swap() function in C++ STL
The unordered_multiset::swap() is a built-in function in C++ STL which swaps the contents of two unordered_multiset
containers.
Note: Both of the containers should have the same type of elements. Sizes of the containers may differ.
Syntax:
unordered_multiset1.swap(unordered_multiset2);
Parameters: The function accepts only one compulsory parameter i.e unordered_multiset2 with which the swapping of unordered_multiset1 is to be done.
Return Value: It does not return any value.
Below programs illustrate the above function.
Program 1:
C++
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
void display(unordered_multiset< int > s)
{
for ( auto it = s.begin(); it != s.end(); it++)
cout << *it<< " " ;
cout<< "\n" ;
}
int main()
{
unordered_multiset< int > s1, s2;
s1 = { 1, 2, 3, 4 };
s2 = { 10, 20, 30, 40, 50 };
cout << "Initial values of s1 are: \n" ;
display(s1);
cout << endl;
cout << "Initial values of s2 are: \n" ;
display(s2);
cout << endl;
s1.swap(s2);
cout << "Final values of s1 are: \n" ;
display(s1);
cout << endl;
cout << "Final values of s2 are: \n" ;
display(s2);
return 0;
}
|
Output:
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
Program 2:
C++
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
void display(unordered_multiset<string> s)
{
for ( auto it = s.begin(); it != s.end(); it++)
cout << *it << " " ;
cout<<endl;
}
int main()
{
unordered_multiset<string> s1, s2;
s1 = { "Geeks" , "for" , "Geeks" };
s2 = { "Computer" , "Science" , "Portal" , "for" , "Geeks" };
cout << "Initial values of s1 are: \n" ;
display(s1);
cout << endl;
cout << "Initial values of s2 are: \n" ;
display(s2);
cout << endl;
s1.swap(s2);
cout << "Final values of s1 are: \n" ;
display(s1);
cout << endl;
cout << "Final values of s2 are: \n" ;
display(s2);
return 0;
}
|
Output:
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
Last Updated :
02 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...