0
0
CppHow-ToBeginner · 3 min read

How to Use std::fill in C++: Syntax and Examples

In C++, std::fill is used to assign a specific value to a range of elements in containers or arrays. You provide the start and end iterators and the value to fill, and it replaces all elements in that range with the given value.
📐

Syntax

The std::fill function requires three arguments: the start iterator, the end iterator, and the value to assign. It sets every element in the range [start, end) to the given value.

  • start: Iterator pointing to the first element to fill.
  • end: Iterator pointing just past the last element to fill.
  • value: The value to assign to each element in the range.
cpp
std::fill(start_iterator, end_iterator, value);
💻

Example

This example shows how to fill an array and a vector with the value 7 using std::fill. It demonstrates replacing all elements in the specified range.

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

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    std::fill(arr, arr + 5, 7); // Fill entire array with 7

    std::cout << "Array after fill: ";
    for (int x : arr) {
        std::cout << x << ' ';
    }
    std::cout << '\n';

    std::vector<int> vec = {10, 20, 30, 40, 50};
    std::fill(vec.begin(), vec.end(), 7); // Fill entire vector with 7

    std::cout << "Vector after fill: ";
    for (int x : vec) {
        std::cout << x << ' ';
    }
    std::cout << '\n';

    return 0;
}
Output
Array after fill: 7 7 7 7 7 Vector after fill: 7 7 7 7 7
⚠️

Common Pitfalls

One common mistake is using std::fill with incorrect iterator ranges, such as passing the end iterator before the start iterator, which leads to no changes or undefined behavior. Another is trying to fill a container that does not support at least forward iterators, which may cause compilation errors.

Also, std::fill replaces existing elements; it does not resize containers. To fill a container that is empty, you must first resize it.

cpp
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v;
    // Wrong: filling empty vector without resizing does nothing
    std::fill(v.begin(), v.end(), 5);

    // Correct: resize first, then fill
    v.resize(5);
    std::fill(v.begin(), v.end(), 5);

    return 0;
}
📊

Quick Reference

  • std::fill(start, end, value): Assigns value to all elements in [start, end).
  • Works with arrays, vectors, and other containers supporting iterators.
  • Does not change container size.
  • Requires valid iterator range where start <= end.

Key Takeaways

Use std::fill to assign the same value to a range of elements efficiently.
Always provide a valid iterator range: start iterator must not come after end iterator.
std::fill does not resize containers; resize first if needed.
Works with arrays, vectors, and other containers supporting iterators.
Avoid using std::fill on empty containers without resizing to prevent no effect.