function template
<algorithm>

std::fill_n

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);
Fill sequence with value
Assigns val to the first n elements of the sequence pointed by first.

The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
8
9
template <class OutputIterator, class Size, class T>
  OutputIterator fill_n (OutputIterator first, Size n, const T& val)
{
  while (n>0) {
    *first = val;
    ++first; --n;
  }
  return first;     // since C++11
}


Parameters

first
Output iterators to the initial position in a sequence of at least n elements that support being assigned a value of type T.
n
Number of elements to fill.
This value shall not be negative.
If negative, the function does nothing.
Size shall be (convertible to) an integral type.
val
Value to be used to fill the range.

Return value

none
An iterator pointing to the element that follows the last element filled.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// fill_n example
#include <iostream>     // std::cout
#include <algorithm>    // std::fill_n
#include <vector>       // std::vector

int main () {
  std::vector<int> myvector (8,10);        // myvector: 10 10 10 10 10 10 10 10

  std::fill_n (myvector.begin(),4,20);     // myvector: 20 20 20 20 10 10 10 10
  std::fill_n (myvector.begin()+3,3,33);   // myvector: 20 20 20 33 33 33 10 10

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}


Output:
myvector contains: 20 20 20 33 33 33 10 10

Complexity

Linear in n: Assigns a value to each element.

Data races

The n first objects at the range pointed by first are modified (each object is modified exactly once).

Exceptions

Throws if either an element assignment or an operation on an iterator throws.
Note that invalid arguments cause undefined behavior.

See also