Back to C++
2025-12-275 min read

fill()

Learn fill() step by step with clear examples and exercises.

Why This Matters

In this lesson, we delve into the fill() method in C++, an essential tool for initializing arrays with a specific value. By understanding its usage and common pitfalls, you'll be better prepared to tackle real-world programming challenges and debug errors that may arise during your coding journey.

Understanding Array Initialization

Initializing arrays can be time-consuming when dealing with large datasets. The fill() method provides a quick and efficient solution for setting all elements of an array to a specific value, making your code more readable and reducing the risk of errors. In interviews, familiarity with this method demonstrates your understanding of C++ standard library functions.

Prerequisites

To fully grasp the fill() method, you should have a solid foundation in:

  • Basic C++ syntax and data types (e.g., arrays)
  • Standard Library Functions (STL) and their importance
  • Understanding of memory allocation and deallocation
  • Knowledge about iterators and iterator ranges

Core Concept

The fill() function is part of the STL algorithms library, which provides a collection of useful functions for manipulating sequences of elements. It takes three arguments: an iterator range (denoting the start and end positions), an input iterator, and the value to fill the array with.

#include <algorithm>
#include <vector>

int main() {
std::vector<int> arr = {1, 2, 3, 4, 5};
std::fill(arr.begin(), arr.end(), 0); // Fill all elements with 0
}

In this example, we first include the necessary headers for the STL algorithms and the vector container. We then declare a vector arr containing integers from 1 to 5. The fill() function is called with the vector's beginning and end iterators as arguments, along with the value to fill the array (0).

Iterator Ranges and Types

It's important to understand that an iterator range consists of two iterators: one pointing to the first element in the sequence, and another pointing just beyond the last element. The fill() function requires these iterator ranges as its first argument, which can be obtained using the container's begin() and end() functions for common containers like vectors and arrays.

Worked Example

Let's consider an example where we have a 2D array representing a chessboard and need to set all black squares to 'X'.

#include <iostream>
#include <vector>

int main() {
const int rows = 8, cols = 8;
std::vector<std::vector<char>> board(rows, std::vector<char>(cols));

// Initialize the chessboard
for (int i = 0; i < rows; ++i) {
if (i % 2 == 0) {
for (int j = 0; j < cols; ++j) {
board[i][j] = 'X';
}
} else {
for (int j = 0; j < cols; ++j) {
board[i][j] = '.';
}
}
}

// Use fill() to set all black squares to 'B'
std::fill(board.begin(), board.end(), std::vector<char>{'.', '.'});
for (int i = 0; i < rows; ++i) {
if (i % 2 == 1) {
for (int j = 0; j < cols; ++j) {
if (board[i][j] != '.') {
board[i][j] = 'B';
}
}
}
}

// Print the modified chessboard
for (const auto &row : board) {
for (char cell : row) {
std::cout << cell << " ";
}
std::cout << "\n";
}
}

In this example, we first initialize a 2D vector representing the chessboard. We then use nested loops to set the initial values of the board, alternating between 'X' and '.' for black and white squares respectively. After that, we fill all elements of the board vector with two dots (.), effectively setting all black squares to their original value. Finally, we loop through the board again, updating any remaining black squares to 'B'.

Common Mistakes

  1. Forgetting to include necessary headers: Make sure you have included `` and any other required headers for your specific use case.
  2. Using incorrect iterator types: Ensure that the iterators passed to fill() are valid and of the correct type (e.g., using vector::iterator with a vector of integers).
  3. Not understanding the order of operations: Be aware that the fill function modifies the elements in-place, so any subsequent operations on the array may be affected by the fill operation.
  4. Trying to use fill() with non-iterable data structures: fill() only works with iterable data structures like arrays and vectors. It cannot be used with primitive types or other non-iterable structures.
  5. Not handling edge cases: Be aware of potential edge cases when using fill(), such as filling an empty container or a container that already contains the desired value.

Edge Case: Empty Containers

Attempting to fill an empty container will result in no change to its contents. To avoid this issue, consider initializing your containers before calling the fill() function.

Practice Questions

  1. Write a program that initializes an array of 10 integers with the value 5 using the fill() method.
  2. Given a 2D vector representing a Sudoku board, write a function that uses the fill() method to mark all empty cells (represented as '.' or '0') with a specific value (e.g., 'X').
  3. Implement a function that takes two vectors of integers and sets all common elements between them to a specified value using the fill() method.
  4. Write a program that initializes an array of 100 random integers between 1 and 100, then fills all even numbers with the value 0 using the fill() method.
  5. Implement a function that takes a 2D vector representing a Sudoku board and checks if it is filled correctly by comparing each row, column, and box with the expected values (e.g., rows should contain unique integers from 1 to 9). If any discrepancies are found, use the fill() method to mark the incorrect cells with an 'X'.

FAQ

  1. Can I use fill() on a 1D array?: Yes, you can use fill() on any iterable data structure, including 1D arrays (arrays of a single dimension).
  2. What happens if I try to fill an empty vector or array with the fill() method?: Attempting to fill an empty container will result in no change to its contents.
  3. Can I use fill() to set specific elements of an array based on their indices?: No, fill() modifies all elements within the specified range. If you need to set specific elements based on their indices, consider using a loop and assignment operator (e.g., arr[i] = value;).
  4. Is there a way to fill an array with a sequence of values instead of a single one?: Yes, you can use the generate() function from the STL algorithms library in combination with fill_n() to fill an array with a sequence of values. For example:
#include <algorithm>
#include <vector>
#include <iostream>

int main() {
std::vector<int> arr(10); // Create a vector of 10 integers

std::generate_n(arr.begin(), arr.size(), [](){ return i++; }); // Fill the array with numbers from 0 to 9
}
fill() | C++ | XQA Learn