std::fill is a C++ STL algorithm defined in the <algorithm> 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).
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> 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;
}
Output
0 0 4 4 4 4 4 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Â
#include <iostream>
#include <algorithm>
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
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main() {
list<int> 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;
}
Output
4 4 4
Explanation: This code updates every element of the list to 4 by calling std::fill from begin() to end()