I was refactoring some code and found there are two places that can be written with the same code except the comparator of a set is less<double> in one place and greater<double> in the other. Something like:
double MyClass::Function1(double val)
{
std::set<double, less<double> > s;
// Do something with s
}
double MyClass::Function2(double val)
{
std::set<double, greater<double> > s;
// Do the same thing with s as in Function1
}
So I thought of doing:
double MyClass::GeneralFunction(double val, bool condition)
{
if(condition)
{
// Select greater as comparator
}
else
{
// Select less as comparator
}
set<double, comparator> s;
// common code
}
I’ve made it work by using my custom comparator functions, like this:
bool my_greater(double lhs, double rhs)
{
return lhs > rhs;
}
bool my_less(double lhs, double rhs)
{
return lhs < rhs;
}
double MyClass::GeneralFunction(double val, bool condition)
{
typedef bool(*Comparator) ( double, double);
Comparator comp = &my_less;
if (condition)
{
comp = &my_greater;
}
std::set<double, Comparator > s(comp);
//....
}
But I would like to use the built-in ones. The problem is I don’t know how to declare the comparator and assign it the built in predicates.
Any help would be greatly appreciated.
Do you really need a runtime check?
Even if you do, you can still use