Defining Ranges using Sentinels

What is a Sentinel in C++?

What is a sentinel in C++?

Abstract art representing computer programming

A sentinel in C++ is an object used to signal the end of a range, allowing algorithms to know when to stop processing. Unlike traditional iterators, which point to specific memory addresses, sentinels provide a more flexible way to define the end of a range.

Sentinels can be compared to iterators using the == and != operators. When the comparison returns true, the algorithm stops.

Sentinels are particularly useful when the endpoint of a range is not known in advance or is determined dynamically during the execution of an algorithm.

For instance, you might use a sentinel to end a range at the first negative number in a list, which is a condition discovered during iteration.

Here is a simple 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 example, the loop stops when it encounters the first negative number, thanks to the custom sentinel.

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