C++ <forward_list> - operator=() Function
The C++ forward_list::operator= function is used to assign new content to the container by replacing the current content.
Syntax
//copy version - copies all elements //of x into the container forward_list& operator= (const forward_list& x); //move version - moves elements of x //into the container forward_list& operator= (forward_list&& x); //initializer forward_list version - copies all //elements of il into the container forward_list& operator= (initializer_list<value_type> il);
Parameters
x |
Specify a forward_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 forward_list::operator= function is used to assign new values to the given forward_list.
#include <iostream> #include <forward_list> using namespace std; int main (){ forward_list<int> flist1{10, 20, 30, 40, 50}; forward_list<int>::iterator it; //copying all content of flist1 into flist2 forward_list<int> flist2; flist2 = flist1; cout<<"flist1 contains:"; for(it = flist1.begin(); it != flist1.end(); ++it) cout<<" "<<*it; cout<<"\nflist2 contains:"; for(it = flist2.begin(); it != flist2.end(); ++it) cout<<" "<<*it; return 0; }
The output of the above code will be:
flist1 contains: 10 20 30 40 50 flist2 contains: 10 20 30 40 50
Example: using move version
Using the move version of operator=, the content of one forward_list can be moved to another forward_list. Consider the following example:
#include <iostream> #include <forward_list> using namespace std; int main (){ forward_list<int> flist1{10, 20, 30, 40, 50}; forward_list<int>::iterator it; cout<<"flist1 contains:"; for(it = flist1.begin(); it != flist1.end(); ++it) cout<<" "<<*it; //moving all content of flist1 into flist2 forward_list<int> flist2; flist2 = move(flist1); cout<<"\nflist1 contains:"; for(it = flist1.begin(); it != flist1.end(); ++it) cout<<" "<<*it; cout<<"\nflist2 contains:"; for(it = flist2.begin(); it != flist2.end(); ++it) cout<<" "<<*it; return 0; }
The output of the above code will be:
flist1 contains: 10 20 30 40 50 flist1 contains: flist2 contains: 10 20 30 40 50
Example: using initializer forward_list version
The initializer forward_list can also be used to assign values into a forward_list container. Consider the example below:
#include <iostream> #include <forward_list> using namespace std; int main (){ //creating empty forward_list forward_list<int> flist; forward_list<int>::iterator it; //creating initializer forward_list initializer_list<int> ilist = {10, 20, 30, 40, 50}; //assigning values of flist using ilist flist = ilist; cout<<"flist contains:"; for(it = flist.begin(); it != flist.end(); ++it) cout<<" "<<*it; return 0; }
The output of the above code will be:
flist contains: 10 20 30 40 50
❮ C++ <forward_list> Library