Skip to content
Related Articles

Related Articles

unordered_set swap() function in C++ STL
  • Difficulty Level : Basic
  • Last Updated : 28 Sep, 2018

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


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

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :