< cpp‎ | algorithm
Revision as of 15:35, 30 December 2012 by SuperBoi45 (Talk | contribs)

Algorithm library
Execution policies (C++17)
Non-modifying sequence operations
Modifying sequence operations
Operations on uninitialized storage
Partitioning operations
Sorting operations
Binary search operations
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations

Numeric operations
C library

Template:ddcl list begin <tr class="t-dsc-header">

Defined in header <algorithm>

<td></td> <td></td> </tr> <tr class="t-dcl ">

<td >
template< class OutputIt, class Size, class T >

void fill_n( OutputIt first, Size count, const T& value );
template< class OutputIt, class Size, class T >

OutputIt fill_n( OutputIt first, Size count, const T& value );

<td class="t-dcl-nopad"> </td> <td > (until C++11)

(since C++11) </td> </tr> Template:ddcl list end

Assigns the given value value to the first count elements in the range beginning at first if count > 0. Does nothing otherwise.



first - the beginning of the range of elements to modify
count - number of elements to modify
value - the value to be assigned
Type requirements
OutputIt must meet the requirements of OutputIterator.

Return value

(none) (until C++11)

Iterator one past the last element assigned if count > 0, first otherwise. (since C++11)


Exactly count assignments, for count > 0.

Possible implementation

template<class OutputIt, class Size, class T>
OutputIt fill_n(OutputIt first, Size count, const T& value)
    for (Size i = 0; i < count; i++) {
        *first++ = value;
    return first;


The following code uses fill_n() to assign -1 to the first half of a vector of integers:

#include <algorithm>
#include <vector>
#include <iostream>
int main()
    std::vector<int> v1{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    std::fill_n(v1.begin(), 5, -1);
    for (vector<int>::iterator it = v1.begin(); it != v1.end(); ++it) {
        std::cout << *it << " ";
    std::cout << "\n";


-1 -1 -1 -1 -1 5 6 7 8 9

See also

Template:cpp/algorithm/dcl list fill