C++ Standard Library C++ STL Library

C++ <algorithm> - fill_n() Function



The C++ algorithm::fill_n function is used to assign val to the first n elements of the sequence pointed by first.

Syntax

template <class OutputIterator, class Size, class T>
  void fill_n (OutputIterator first, 
               Size n, 
               const T& val);
template <class OutputIterator, class Size, class T>
  OutputIterator fill_n (OutputIterator first, 
                         Size n, 
                         const T& val);

Parameters

first Specify initial position of the output iterator.
n Specify number of elements to be filled.
val Specify the value to be filled.

Return Value

Returns an iterator pointing to the element that follows the last element filled or None(in C++98).

Time Complexity

Linear i.e, Θ(n).

Example:

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

#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 first five element as 10
  fill_n(vec.begin(), 5, 10);

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

  //fill two elements as 100 starting 
  //from third element
  fill_n(vec.begin()+2, 2, 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 10 0 0 0 0 0
vec contains: 10 10 100 100 10 0 0 0 0 0

❮ C++ <algorithm> Library