I have a few loops that I need in my program. I can write out the pseudo code, but I\'m not entirely sure how to write them logically.
I need -
if (num is
This is for future visitors more so than a beginner. For a more general, algorithm-like solution, you can take a list of starting and ending values and check if a passed value is within one of them:
template
bool in_any_interval(It first, It last, const Elem &val) {
return std::any_of(first, last, [&val](const auto &p) {
return p.first <= val && val <= p.second;
});
}
For simplicity, I used a polymorphic lambda (C++14) instead of an explicit pair
argument. This should also probably stick to using <
and ==
to be consistent with the standard algorithms, but it works like this as long as Elem
has <=
defined for it. Anyway, it can be used like this:
std::pair intervals[]{
{11, 20}, {31, 40}, {51, 60}, {71, 80}, {91, 100}
};
const int num = 15;
std::cout << in_any_interval(std::begin(intervals), std::end(intervals), num);
There's a live example here.