How to Create a Custom Sentinel in C++

How do you create a custom sentinel in C++?

Creating a custom sentinel in C++ involves defining a struct or class that includes the necessary comparison operators to determine when an iteration should stop. The sentinel does not need to be an iterator; it simply needs to be able to compare itself to an iterator.

Here's an example of creating a custom sentinel that stops a loop when encountering a negative value:

#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 Sentinel struct has an operator==() method that takes an iterator and returns true if the value pointed to by the iterator is negative. This custom sentinel allows the loop to stop when it encounters the first negative number.

By using custom sentinels, you can define complex stopping conditions tailored to your specific needs, providing greater flexibility and control over your ranges and algorithms.

Defining Ranges using Sentinels

An alternative way of defining ranges, and why we sometimes need to use them

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

What is a Sentinel in C++?
What is a sentinel in C++?
Why Use Sentinels Instead of End Iterators in C++?
Why use sentinels instead of end iterators in C++?
Using Sentinels with Standard Algorithms in C++
How can sentinels be used with standard algorithms in C++?
How Do Template Sentinels Work in C++?
How do template sentinels work in C++?
How to Determine the Size of a Range Defined by a Sentinel in C++
How can you determine the size of a range defined by a sentinel?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant