C++ set - operator=() Function
The C++ set::operator= function is used to assign new content to the container by replacing the current content.
Syntax
//copies all elements of x into the container set& operator= (const set& x);
//copy version - copies all elements //of x into the container set& operator= (const set& x); //move version - moves elements of x //into the container set& operator= (set&& x); //initializer list version - copies all //elements of il into the container set& operator= (initializer_list<value_type> il);
Parameters
x |
Specify a 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.
- Up to logarithmic i.e, Θ(nlog(n)). Linear i.e, Θ(n) if il is already sorted.
Example: using copy version
In the example below, the set::operator= function is used to assign new values to the given set.
#include <iostream> #include <set> using namespace std; int main (){ set<int> set1{15, 5, 23, 78, 41}; set<int>::iterator it; //copying all content of set1 into set2 set<int> set2; set2 = set1; cout<<"The set1 contains:"; for(it = set1.begin(); it != set1.end(); ++it) cout<<" "<<*it; cout<<"\nThe set2 contains:"; for(it = set2.begin(); it != set2.end(); ++it) cout<<" "<<*it; return 0; }
The output of the above code will be:
The set1 contains: 5 15 23 41 78 The set2 contains: 5 15 23 41 78
Example: using move version
Using the move version of operator=, the content of one set can be moved to another set. Consider the following example:
#include <iostream> #include <set> using namespace std; int main (){ set<int> set1{15, 5, 23, 78, 41}; set<int>::iterator it; cout<<"The set1 contains:"; for(it = set1.begin(); it != set1.end(); ++it) cout<<" "<<*it; //moving all content of set1 into set2 set<int> set2; set2 = move(set1); cout<<"\nThe set1 contains:"; for(it = set1.begin(); it != set1.end(); ++it) cout<<" "<<*it; cout<<"\nThe set2 contains:"; for(it = set2.begin(); it != set2.end(); ++it) cout<<" "<<*it; return 0; }
The output of the above code will be:
The set1 contains: 5 15 23 41 78 The set1 contains: The set2 contains: 5 15 23 41 78
Example: using initializer list version
The initializer list can also be used to assign values into a set container. Consider the example below:
#include <iostream> #include <set> using namespace std; int main (){ //creating empty set set<int> MySet; set<int>::iterator it; //creating initializer list initializer_list<int> ilist = {15, 5, 23, 78, 41}; //assigning values of MySet using ilist MySet = ilist; cout<<"MySet contains:"; for(it = MySet.begin(); it != MySet.end(); ++it) cout<<" "<<*it; return 0; }
The output of the above code will be:
MySet contains: 5 15 23 41 78
❮ C++ <set> Library