Skip to content
Related Articles

Related Articles

forward_list::operator= in C++ STL

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 26 Jul, 2018
View Discussion
Improve Article
Save Article


Forward list in STL implements singly linked list. Introduced from C++11, forward lists are useful than other containers for insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from the list by the fact that forward list keeps track of the location of only next element while list keeps track to both next and previous elements.

forward_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 :

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

Examples:

Input  :  myflist1 = 1, 2, 3
          myflist2 = 3, 2, 1, 4
          myflist1 = myflist2;
Output :  myflist1 = 3, 2, 1, 4

Input  :  myflist1 = 2, 6, 1, 5
          myflist2 = 3, 2
          myflist1 = myflist2;
Output :  myflist1 = 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 <forward_list>
#include <iostream>
using namespace std;
   
int main()
{
    forward_list<int> myflist1{ 1, 2, 3 };
    forward_list<int> myflist2{ 3, 2, 1, 4 };
    myflist1 = myflist2;
    cout << "myflist1 = ";
    for (auto it = myflist1.begin(); it != myflist1.end(); ++it)
        cout << ' ' << *it;
    return 0;
}


Output:

myflist1 = 3 2 1 4
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!