Open In App

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: 






// 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(): ";
    // element
    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;
}

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

 

Time complexity: O(1)
Auxiliary Space: O(1)




Article Tags :
C++