C++ Algorithm Library - fill_n() Function



Description

The C++ function std::algorithm::fill_n() assigns value to the first n elements of the sequence pointed by first.

Declaration

Following is the declaration for std::algorithm::fill_n() function form std::algorithm header.

C++98

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

Parameters

  • first − Output iterators to the initial positions.

  • n − Number of elements to fill.

  • val − Value to be used to fill the range.

Return value

None

Exceptions

Throws an exception if either element assignment or an operation on an iterator throws exception.

Please note that invalid parameters cause undefined behavior.

Time complexity

Linear.

Example

The following example shows the usage of std::algorithm::fill_n() function.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(void) {
   vector<int> v(5, 1);

   fill_n(v.begin() + 2, 3, 4);

   cout << "Vector contains following elements" << endl;

   for (auto it = v.begin(); it != v.end(); ++it)
      cout << *it << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Vector contains following elements
1
1
4
4
4
algorithm.htm
Advertisements