Related Articles
set::swap() in C++ STL
• Difficulty Level : Basic
• 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'}
```
 `// CPP program to illustrate``// Implementation of swap() function``#include ``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

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up