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.
An alternative way of defining ranges, and why we sometimes need to use them