Created
March 7, 2014 12:13
-
-
Save martinmoene/9410391 to your computer and use it in GitHub Desktop.
std::between() an idea by Niels Dekker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// std::between() an idea by Niels Dekker | |
#include <functional> | |
namespace std { | |
template<class T> | |
bool between(T const& val, T const& lo, T const& hi) | |
{ | |
return between( val, lo, hi, std::less<T>() ); | |
} | |
template<class T, class Compare> | |
bool between(T const& val, T const& lo, T const& hi, Compare comp) | |
{ | |
return comp(lo, val) && comp(val, hi); | |
} | |
} | |
#include <cassert> | |
#include <cstdlib> | |
#include <limits> | |
int main() | |
{ | |
assert( std::between( rand(), 0, RAND_MAX ) ); | |
assert( ! std::between( 2, 3, 7 ) ); | |
assert( ! std::between( 3, 3, 7 ) ); | |
assert( std::between( 4, 3, 7 ) ); | |
assert( std::between( 5, 3, 7 ) ); | |
assert( std::between( 6, 3, 7 ) ); | |
assert( ! std::between( 7, 3, 7 ) ); | |
assert( ! std::between( 8, 3, 7 ) ); | |
assert( ! std::between( 2.0, 3.0, 7.0 ) ); | |
assert( ! std::between( 3.0, 3.0, 7.0 ) ); | |
assert( std::between( 4.0, 3.0, 7.0 ) ); | |
assert( std::between( 5.0, 3.0, 7.0 ) ); | |
assert( std::between( 6.0, 3.0, 7.0 ) ); | |
assert( ! std::between( 7.0, 3.0, 7.0 ) ); | |
assert( ! std::between( 8.0, 3.0, 7.0 ) ); | |
assert( ! std::between( 1.0 - std::numeric_limits<double>::epsilon(), 1.0, 7.0 ) ); | |
assert( ! std::between( 1.0 , 1.0, 7.0 ) ); | |
assert( std::between( 1.0 + std::numeric_limits<double>::epsilon(), 1.0, 7.0 ) ); | |
} | |
// cl -nologo -EHsc between.cpp && between | |
// g++ -Wall -Wextra -Weffc++ -std=c++11 -o between.exe between.cpp && between |
Author
martinmoene
commented
Apr 26, 2021
via email
On 25-Apr-21 21:18, Oliver Smith wrote:
***@***.**** commented on this gist.
-------------------------------------------------------------------------------
If you make the default for comp be std::less_equal you could consolidate to
a single implementation?
—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
<https://gist.github.com/9410391#gistcomment-3719424>, or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAPIDOT2SPYHZVBPJFEJNZ3TKRTJ3ANCNFSM43RSSICQ>.
Indeed, that's possible for C++14 and later, but not for C++11.
template<class T, class Compare = std::less_equal<> >
bool between(T const& val, T const& lo, T const& hi, Compare comp = Compare{} )
{
return comp(lo, val) && comp(val, hi);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment