Forward_list::operator = in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of forward_list::operator = in C++.

What is a Forward_list in STL?

Forward list are sequence containers that allow constant time insert and erase operations anywhere within the sequence. Forward list are implement as a singly-linked lists. The ordering is kept by the association to each element of a link to the next element in the sequence.

What is forward_list::operator =?

Forward_list::operator = is used to assign the new values to the forward_list container by replacing the already existing ones. This operator also modifies the size of the forward_list container according to the new values.

Syntax

Forward_container1 = (forward_container2);

This function accepts another forward_list container of the same type.

Return Value

It returns “*this” pointer.

In the below code we are creating two forward lists and inserting elements to it and after that we will use ‘=’ operator to overwrite the elements of a forward list 1 with the forward list 2.

Example

 Live Demo

#include <forward_list>
#include <iostream>
using namespace std;
int main(){
   forward_list<int> forwardList1 = {10, 20, 30 };
   forward_list<int> forwardList2 = { 0, 1, 2, 3 };
   forwardList1 = forwardList2;
   cout << "my forwardList1 after using = operator with forwardList2\n";
   for (auto i = forwardList1.begin(); i != forwardList1.end(); ++i)
      cout << ' ' << *i;
   return 0;
}

Output

If we run the above code it will generate the following output

my forwardList1 after using = operator with forwardList2
0 1 2 3

Example

In the below code we are creating two forward lists and inserting elements to it and after that we will use ‘=’ operator to overwrite the elements of a forward list 1 with the forward list 2. The main task now is to check the status of forward list 2 i.e. whether it will also gets changed or not

 Live Demo

#include <forward_list>
#include <iostream>
using namespace std;
int main(){
   forward_list<int> forwardList1 = {10, 20, 30 };
   forward_list<int> forwardList2 = { 0, 1, 2, 3 };
   forwardList1 = forwardList2;
   cout << "my forwardList1 after using = operator with forwardList2\n";
   for (auto i = forwardList1.begin(); i != forwardList1.end(); ++i)
      cout << ' ' << *i;
   cout << "\n my forwardList2 after using = operator with forwardList1\n";
   for (auto i = forwardList2.begin(); i != forwardList2.end(); ++i)
      cout << ' ' << *i;
   return 0;
}

Output

If we run the above code it will generate the following output

my forwardList1 after using = operator with forwardList2
0 1 2 3
my forwardList2 after using = operator with forwardList1
0 1 2 3
raja
Published on 02-Mar-2020 12:25:47
Advertisements