I have a function: bool inBounds(int value, int low, int high). Is there an STL equivalent that does useful things (takes variables of different types, specifically)? I can’t find one using Google, and I’d prefer to re-use rather than re-write.
I have a function: bool inBounds(int value, int low, int high) . Is there
Share
In C++17, there’s no direct equivalent of a function like this, but for smaller types with fast equality comparisons you could use
std::clamp:Alternatively, you can just write your own function to test for this:
This checks if
valueis in the range [low, high). If you want the range [low, high], you’d write this asNote how this is defined purely in terms of
operator <, which means that any class that supports justoperator <can be used here.Similarly, here’s one using custom comparators:
This latter one has the nice advantage that
lowandhighdon’t have to be the same type asvalue, and as long as the comparator can handle that it will work just fine.Hope this helps!