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'}
filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

set1 =  5 6 7 8
set2 =  1 2 3 4

Time complexity: Constant



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.