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