# 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 ` `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

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next