Defining Ranges using Sentinels

Why Use Sentinels Instead of End Iterators in C++?

Why use sentinels instead of end iterators in C++?

Abstract art representing computer programming

Using sentinels instead of end iterators in C++ provides greater flexibility, especially in situations where the endpoint of a range is not known in advance or is determined dynamically. Sentinels can define stopping conditions that are more complex than simply reaching the end of a container.

For example, if you want to iterate through a range until a specific condition is met, such as encountering a negative number, a sentinel can be used to stop the iteration when that condition is fulfilled. Here’s a practical example:

#include <iostream>
#include <vector>

struct Sentinel {
  bool operator==(
    std::vector<int>::const_iterator iter) const {
    return *iter < 0;
  }
};

int main() {
  std::vector<int> numbers{1, 4, 3, 8, -2, 5};
  Sentinel s;

  for (auto it = numbers.begin(); it != s; ++it) {
    std::cout << *it << ", ";
  }
}
1, 4, 3, 8,

In this case, the iteration stops as soon as the first negative number is encountered, thanks to the custom sentinel.

Using sentinels can simplify code, making it more readable and maintainable by clearly expressing the termination condition. They are also more versatile, allowing for a wider range of termination criteria beyond just reaching the end of a container. This makes sentinels a powerful tool for controlling the flow of algorithms in C++.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved