unordered_set swap() function in C++ STL

The unordered_set::swap() method is a builtin function in C++ STL which is used to exchange values of two unordered_set containers. It swaps the element of two unordered_set containers. The sizes may differ but it swaps elements and changes the order of elements also.

Syntax:

unordered_set_firstname.swap(unordered_set_secondname)

Parameter: The function accepts one mandatory parameter second_name which specifies the second unordered_set which is to be swapped with the first one.



Return Value: This function doesn’t returns anything.

Below program illustrates the unordered_set::swap() function:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the
// unordered_set_swap() function
#include <iostream>
#include <unordered_set>
  
using namespace std;
  
int main()
{
  
    unordered_set<int> arr1 = { 1, 2, 3, 4, 5 };
    unordered_set<int> arr2 = { 5, 6, 7, 8, 9 };
  
    cout << "The elements of arr1 before swap(): ";
   
    for (auto it = arr1.begin(); it != arr1.end(); it++) {
        cout << *it << " ";
    }
  
    cout << "\nThe elements of arr2 before swap(): ";
    for (auto it = arr2.begin(); it != arr2.end(); it++) {
        cout << *it << " ";
    }
  
    // inbuilt swap function to swap
    // elements of two unordered_set
    swap(arr1, arr2);
  
    cout << "\n\nThe elements of arr1 after swap(): ";
    // elemen
    for (auto it = arr1.begin(); it != arr1.end(); it++) {
        cout << *it << " ";
    }
  
    cout << "\nThe elements of arr2 after swap(): ";
    for (auto it = arr2.begin(); it != arr2.end(); it++) {
        cout << *it << " ";
    }
  
    return 0;
}

chevron_right


Output:

The elements of arr1 before swap(): 5 1 2 3 4 
The elements of arr2 before swap(): 9 5 6 7 8 

The elements of arr1 after swap(): 9 5 6 7 8 
The elements of arr2 after swap(): 5 1 2 3 4


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.