unordered_set operator= in C++ STL

The ‘=’ is an operator in C++ STL which copies (or moves) an unordered_set to another unordered_set and unordered_set::operator= is the corresponding operator function. There are three versions of this function.

  • The first version takes reference of an unordered_set as an argument and copies it to an unordered_set.
  • The second version performs a move assignment i.e it moves the content of an unordered_set to another unordered_set.
  • The third version assigns contents of an initializer list to an unordered_set.


uset.operator= ( unordered_set& us )
uset.operator= ( unordered_set&& us )
uset.operator= ( initializer list )


  • The first version takes the reference of an unordered_set as argument.
  • The second version takes the r-value reference of an unordered_set as argument.
  • The third version takes an initializer list as argument.

Return value: All of them returns the value of this pointer(*this) .

Below program illustrates the unordered_set::operator= in C++.





// C++ code to illustrate the method 
// unordered_set::operator=()
#include <iostream>
#include <unordered_set>
using namespace std;
// merge function
template <class T>
T merge(T a, T b)
    T t(a);
    t.insert(b.begin(), b.end());
    return t;
int main()
    unordered_set<int> sample1, sample2, sample3;
    // List initialization
    sample1 = { 7, 8, 9 };
    sample2 = { 9, 10, 11, 12 };
    // Merge both lists
    sample3 = merge(sample1, sample2);
    // copy assignment 
    sample1 = sample3;
    // Print the unordered_set list
    for (auto it = sample1.begin(); it != sample1.end(); ++it)
        cout << *it << " ";
    cout << endl;
    for (auto it = sample2.begin(); it != sample2.end(); ++it)
        cout << *it << " ";
    cout << endl;
    for (auto it = sample3.begin(); it != sample3.end(); ++it)
        cout << *it << " ";
    cout << endl;



10 11 12 7 8 9 
12 11 10 9 
10 11 12 7 8 9

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details

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 or mail your article to 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.

Improved By : ankit15697