Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


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 below example, 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 below example:

#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