fill in C++ STL (original) (raw)
Last Updated : 20 Jan, 2026
std::fill is a C++ STL algorithm defined in the header that assigns a specified value to every element in a given range [first, last). It works with arrays and STL containers that provide at least forward iterators (such as vector, list, and deque).
C++ `
#include #include #include using namespace std;
int main() { vector v(8);
// Fill elements from index 2 to index 6 with value 4
fill(v.begin() + 2, v.end() - 1, 4);
for (int x : v)
cout << x << " ";
return 0;}
`
**Explanation: This code fills the elements from index 2 to 6 of the vector with the value 4 using std::fill.
Syntax
std::fill(first, last, value);
Parameters
- **first: Iterator pointing to the first element of the range.
- **last: Iterator pointing to the position just after the last element of the range.
- **value: The value to be assigned to each element in the range.
Note: The range is half-open — first is included, but last is excluded.
**Example 1: Using std::fill with an Array
C++ `
#include #include using namespace std;
int main() { int arr[10];
// Fill entire array with value 4
fill(arr, arr + 10, 4);
for (int i = 0; i < 10; i++)
cout << arr[i] << " ";
return 0;}
`
Output
4 4 4 4 4 4 4 4 4 4
**Explanation: This code assigns the value 4 to all elements of the array by applying std::fill on the entire array range.
**Example 2: Using std::fill with a List
C++ `
#include #include #include using namespace std;
int main() { list ml = {10, 20, 30};
// Fill all elements of the list with value 4
fill(ml.begin(), ml.end(), 4);
for (int x : ml)
cout << x << " ";
return 0;}
`
**Explanation: This code updates every element of the list to 4 by calling std::fill from begin() to end()