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