C++ Algorithm Library - fill() Function


Advertisements

Description

The C++ function std::algorithm::fill() assigns certain value to a range of elements.

Declaration

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

C++98

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

Parameters

  • first − Forward iterators to the initial positions.

  • last − Forward iterators to the final positions.

  • 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 in the distance between first to last.

Example

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

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

using namespace std;

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

   fill(v.begin(), v.end(), 1);

   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
1
1
1
algorithm.htm
Advertisements