C++ Standard Library C++ STL Library

C++ <forward_list> - assign() Function



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 example below, 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> flist1;
  forward_list<int> flist2;
  forward_list<int> flist3;
  forward_list<int>::iterator it;

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

  //using range version 
  flist2.assign(flist1.begin(), flist1.end());  

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

  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<<" ";

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

  return 0;
}

The output of the above code will be:

flist1 contains: 10 10 10 10 10 
flist2 contains: 10 10 10 10 10 
flist3 contains: 10 20 30 

❮ C++ <forward_list> Library