C++ Standard Library C++ STL Library

C++ <list> - assign() Function



The C++ list::assign function is used to assign new values to the 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);
//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 list.
val Specify the value to fill the list with. Each of the 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 list::assign function is used to assign new values to the given list, replacing its old values.

#include <iostream>
#include <list>
using namespace std;
 
int main (){
  list<int> list1;
  list<int> list2;
  list<int> list3;
  list<int>::iterator it;

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

  //using range version 
  list2.assign(list1.begin(), list1.end());  

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

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

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

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

  return 0;
}

The output of the above code will be:

list1 contains: 10 10 10 10 10 
list2 contains: 10 10 10 10 10 
list3 contains: 10 20 30 

❮ C++ <list> Library