std::map
takes the comparison object as a template parameter, so to do what you want you need a type that you can change the behaviour at runtime.
struct MoreOrLess
{
bool useLess;
template <class T, class U>
bool operator()(const T &t, const U &u) const
{
if(useLess) return t < u;
else return t > u;
}
};
struct MyStruct
{
std::map<int, double, MoreOrLess> my_map;
MyStruct(bool dir) :my_map(MoreOrLess{dir}) {}
};
This way the comparison functor has the same type (for use in std::map
) regardless of using std::less
or std::greater
.