How to Use std::fill in C++: Syntax and Examples
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.
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.
#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; }
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.
#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
valueto 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.