std::fill (C++)

std::fill is a higher-level function from the C++ Standard Library that is type-safe and more versatile, supporting all kinds of types, not just POD types or raw memory.

vector<int> vec(10);
fill(vec.begin(), vec.end(), 42);  // Fill the vector with 42

Use Case: Used to fill containers (like std::vector, std::array, or C++ arrays) with a specific value. It respects the types and boundaries of the container or range. Advantages:

  • Type-safe, meaning it respects the types of the elements being filled.
  • Can be used with non-trivial types (e.g., objects, classes) as well as primitive types.
  • It can fill arbitrary ranges of containers, not just contiguous blocks of memory.