Defining Ranges using Sentinels

How to Create a Custom Sentinel in C++

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

Abstract art representing computer programming

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.

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:

  • 124 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