set::swap() in C++ STL
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'}
// CPP program to illustrate // Implementation of swap() function #include <bits/stdc++.h> using namespace std; int main() { // Take any two sets set< int > set1{ 1, 2, 3, 4 }; set< int > set2{ 5, 6, 7, 8 }; // Swap elements of sets set1.swap(set2); // Print the first set cout << "set1 = " ; for ( auto it = set1.begin(); it != set1.end(); ++it) cout << ' ' << *it; // Print the second set 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
Recommended Posts:
- Minimum cells to be flipped to get a 2*2 submatrix with equal elements
- Nested Loops in C++ with Examples
- _Find_first() function in C++ bitset with Examples
- _Find_next() function in C++ bitset with Examples
- Left-Right traversal of all the levels of N-ary tree
- Difference between Iterators and Pointers in C/C++ with Examples
- ostream::seekp(pos) method in C++ with Exmaples
- Default Methods in C++ with Examples
- C++ Tutorial
- Hello World Program : First program while learning Programming
- Difference between Argument and Parameter in C/C++ with Examples
- <cfloat> float.h in C/C++ with Examples
- C/C++ #include directive with Examples
- C/C++ if else statement with Examples
- C/C++ if statement with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.