set::swap() in C++ STL
Last Updated :
14 Jan, 2018
Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element.
set::swap()
This function is used to exchange the contents of two sets but the sets must be of same type, although sizes may differ.
Syntax:
set1.swap(set2)
Return value: None
Examples:
Input : set1 = {1, 2, 3, 4}
set2 = {5, 6, 7, 8}
set1.swap(set2);
Output : set1 = {5, 6, 7, 8}
set2 = {1, 2, 3, 4}
Input : set1 = {'a', 'b', 'c', 'd'}
set2 = {'w', 'x', 'y', 'z'}
set1.swap(set2);
Output : set1 = {'w', 'x', 'y', 'z'}
set2 = {'a', 'b', 'c', 'd'}
#include <bits/stdc++.h>
using namespace std;
int main()
{
set< int > set1{ 1, 2, 3, 4 };
set< int > set2{ 5, 6, 7, 8 };
set1.swap(set2);
cout << "set1 = " ;
for ( auto it = set1.begin();
it != set1.end(); ++it)
cout << ' ' << *it;
cout << endl
<< "set2 = " ;
for ( auto it = set2.begin();
it != set2.end(); ++it)
cout << ' ' << *it;
return 0;
}
|
Output:
set1 = 5 6 7 8
set2 = 1 2 3 4
Time complexity: Constant
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...