C++ unordered_set - operator=() Function
The C++ unordered_set::operator= function is used to assign new content to the container by replacing the current content.
Syntax
//copy version - copies all elements //of x into the container unordered_set& operator= (const unordered_set& x); //move version - moves elements of x //into the container unordered_set& operator= (unordered_set&& x); //initializer list version - copies all //elements of il into the container unordered_set& operator= (initializer_list<value_type> il);
Parameters
x |
Specify a unordered_set object of same type. |
il |
Specify an initializer_list object. |
Return Value
Returns *this.
Time Complexity
- Linear i.e, Θ(n) for copy version and move version.
- On average: Linear i.e, Θ(n). Worst case: quadratic i.e, Θ(n2).
Example: using copy version
In the example below, the unordered_set::operator= function is used to assign new values to the given unordered_set.
#include <iostream> #include <unordered_set> using namespace std; int main (){ unordered_set<int> uSet1{15, 5, 23, 78, 41}; unordered_set<int>::iterator it; //copying all content of uSet1 into uSet2 unordered_set<int> uSet2; uSet2 = uSet1; cout<<"uSet1 contains:"; for(it = uSet1.begin(); it != uSet1.end(); ++it) cout<<" "<<*it; cout<<"\nuSet2 contains:"; for(it = uSet2.begin(); it != uSet2.end(); ++it) cout<<" "<<*it; return 0; }
The output of the above code will be:
uSet1 contains: 41 78 23 5 15 uSet2 contains: 41 78 23 5 15
Example: using move version
Using the move version of operator=, the content of one unordered_set can be moved to another unordered_set. Consider the following example:
#include <iostream> #include <unordered_set> using namespace std; int main (){ unordered_set<int> uSet1{15, 5, 23, 78, 41}; unordered_set<int>::iterator it; cout<<"uSet1 contains:"; for(it = uSet1.begin(); it != uSet1.end(); ++it) cout<<" "<<*it; //moving all content of uSet1 into uSet2 unordered_set<int> uSet2; uSet2 = move(uSet1); cout<<"\nuSet1 contains:"; for(it = uSet1.begin(); it != uSet1.end(); ++it) cout<<" "<<*it; cout<<"\nuSet2 contains:"; for(it = uSet2.begin(); it != uSet2.end(); ++it) cout<<" "<<*it; return 0; }
The output of the above code will be:
uSet1 contains: 41 78 23 5 15 uSet1 contains: uSet2 contains: 41 78 23 5 15
Example: using initializer list version
The initializer list can also be used to assign values into a unordered_set container. Consider the example below:
#include <iostream> #include <unordered_set> using namespace std; int main (){ //creating empty unordered_set unordered_set<int> uSet; unordered_set<int>::iterator it; //creating initializer list initializer_list<int> ilist = {15, 5, 23, 78, 41}; //assigning values of uSet using ilist uSet = ilist; cout<<"uSet contains:"; for(it = uSet.begin(); it != uSet.end(); ++it) cout<<" "<<*it; return 0; }
The output of the above code will be:
uSet contains: 78 23 5 41 15
❮ C++ <unordered_set> Library