std::fill_n

From Cppreference

Jump to: navigation, search
Defined in header <algorithm>

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

Assigns the given value value to the first count elements in the range beginning at first.

Contents

Parameters

first - the beginning of the range of elements to modify
count - number of elements to modify
value - the value to be assigned

Return value

(none)

Complexity

linear in count

Equivalent function

template<class OutputIterator, class Size, class T>
void fill(OutputIterator first, Size count, const T& value)
{
    for (Size i = 0; i < count; i++) {
        *first++ = value;
    }
}

Example

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()
{
    int data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
    std::vector<int> v1(data, data+10);
 
    std::fill_n(v1.begin(), 5, -1);
 
    for (vector<int>::iterator it = v1.begin(); it != v1.end(); ++it) {
        std::cout << *it << " ";
    }
 
    return 0;
}

Output:

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

See also

fill
assigns a range of elements a certain value
(function template)
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox
In other languages