Skip to content
Related Articles

Related Articles

Improve Article
list::operator= in C++ STL
  • Last Updated : 12 Jan, 2018

Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists.

list::operator=

This operator is used to assign new contents to the container by replacing the existing contents.
It also modifies the size according to the new contents.

Syntax :

listname1 = (listname2)
Parameters :
Another container of the same type.
Result :
Assign the contents of the container passed as 
parameter to the container written on left side of the operator.

Examples:

Input  :  mylist1 = 1, 2, 3
          mylist2 = 3, 2, 1, 4
          mylist1 = mylist2;
Output :  mylist1 = 3, 2, 1, 4

Input  :  mylist1 = 2, 6, 1, 5
          mylist2 = 3, 2
          mylist1 = mylist2;
Output :  mylist1 = 3, 2

Errors and Exceptions

1. If the containers are of different types, an error is thrown.
2. It has a basic no exception throw guarantee otherwise.




// CPP program to illustrate
// Implementation of = operator
#include <iostream>
#include <list>
using namespace std;
  
int main()
{
    list<int> mylist1{ 1, 2, 3 };
    list<int> mylist2{ 3, 2, 1, 4 };
    mylist1 = mylist2;
    cout << "mylist1 = ";
    for (auto it = mylist1.begin();
              it != mylist1.end(); ++it)
        cout << ' ' << *it;
    return 0;
}

Output:

mylist1 = 3 2 1 4
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :