Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::fill: assigning one value across a range

std::fill assigns value to every element in the half-open iterator range [first, last) and returns void in C++23.

Version: C++23

Syntax

template<class ForwardIterator, class T>
constexpr void std::fill(
    ForwardIterator first, ForwardIterator last, const T& value);

template<class ExecutionPolicy, class ForwardIterator, class T>
void std::fill(ExecutionPolicy&& exec,
    ForwardIterator first, ForwardIterator last, const T& value);

std::fill(first, last, value) from <algorithm> performs exactly N assignments through the iterators in the range, where N is its element count. value must be writable through the iterator. The no-policy overload is constexpr and requires forward iterators.

The example fills only the middle of an array with 9 and prints 1 9 9 4; the element at last is outside the range. An empty range performs zero assignments. When a returned iterator or a whole range overload is useful, ranges::fill provides a different interface.

first and last must describe a valid range and its elements must be writable; a const range cannot be filled. An assignment exception in the no-policy form propagates and earlier elements can already be changed. With a standard execution policy, an uncaught exception from an element operation calls std::terminate. If temporary memory required for parallelization is unavailable, the policy overload instead throws std::bad_alloc.

Examples

#include <algorithm>
#include <array>
#include <iostream>

int main() {
    std::array values{1, 2, 3, 4};
    std::fill(values.begin() + 1, values.end() - 1, 9);
    std::cout << values[0] << ' ' << values[1] << ' '
              << values[2] << ' ' << values[3] << '\n';
}

Result

1 9 9 4

std::fill → 1 9 9 4

Sources