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


The C++ forward_list::assign function is used to assign new values to the forward_list, replacing its old values, and modifying its size if necessary.

Syntax

//range version
template <class InputIterator>
  void assign (InputIterator first, InputIterator last);

//fill version
void assign (size_type n, const value_type& val);

//initializer list version
void assign (initializer_list<value_type> ilist);

Parameters

first Specify the starting position of InputIterator. The range used by InputIterator is [first,last).
last Specify the last position of InputIterator. The range used by InputIterator is [first,last).
n Specify new size of the forward_list.
val Specify the value to fill the forward_list with. Each of the forward_list will be initialized to a copy of this value.
ilist Specify the initializer_list object.

Return Value

None.

Time Complexity

Linear i.e, Θ(n)

Example:

In the below example, the forward_list::assign function is used to assign new values to the given forward_list, replacing its old values.

#include <iostream>
#include <forward_list>
using namespace std;
 
int main (){
  forward_list<int> f_list1;
  forward_list<int> f_list2;
  forward_list<int> f_list3;
  forward_list<int>::iterator it;

  //using fill version - size 5 with value 10
  f_list1.assign(5, 10);

  //using range version 
  f_list2.assign(f_list1.begin(), f_list1.end());  

  //using initializer list version 
  int MyList[] = {10, 20, 30, 40, 50};
  f_list3.assign(MyList, MyList+3); 

  cout<<"f_list1 contains: ";
  for(it = f_list1.begin(); it != f_list1.end(); it++)
    cout<<*it<<" ";

  cout<<"\nf_list2 contains: ";
  for(it = f_list2.begin(); it != f_list2.end(); it++)
    cout<<*it<<" ";

  cout<<"\nf_list3 contains: ";
  for(it = f_list3.begin(); it != f_list3.end(); it++)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

f_list1 contains: 10 10 10 10 10 
f_list2 contains: 10 10 10 10 10 
f_list3 contains: 10 20 30 

❮ C++ - Forward List