C++ Standard Library C++ STL Library

C++ <algorithm> - fill() Function



The C++ algorithm::fill function is used to assign val to all elements in the range [first, last).

Syntax

template <class ForwardIterator, class T> 
  void fill (ForwardIterator first, 
             ForwardIterator last, 
             const T& val);

Parameters

first Specify initial position of the forward iterator. The range used is [first,last).
last Specify final position of the forward iterator. The range used is [first,last).
val Specify the value to be filled.

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::fill function is used to fill the specified value in a given range.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
 
int main (){
  vector<int> vec(10);
  vector<int>::iterator it;

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

  //fill 10 in a given range
  fill(vec.begin(), vec.begin()+4, 10);

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

  //fill 100 in a given range
  fill(vec.begin()+2, vec.begin()+4, 100);

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

  return 0;
}

The output of the above code will be:

vec contains: 0 0 0 0 0 0 0 0 0 0
vec contains: 10 10 10 10 0 0 0 0 0 0
vec contains: 10 10 100 100 0 0 0 0 0 0

❮ C++ <algorithm> Library