If you want to sort according to the relation defined by your LessA
comparator, just pass an instance of LessA
as the third argument (and, since you are using C++11, prefer the global std::begin()
and std::end()
functions):
std::sort(std::begin(a), std::end(a), LessA());
// ^^^^^^^
Now if your LessA()
expresses the <
relation and you want to sort according to the opposite criterion, you could do:
std::sort(std::begin(a), std::end(a),
[] (A const& a1, A const& a2))
{
return LessA()(a2, a1);
}
Another thing you could do is to let your custom comparator accept an argument that determines how it should perform the comparison:
class CompA {
bool lessThan;
public:
CompA(bool lessThan) : _lessThan(lessThan) { }
bool operator()(const A& a1, const A& a2) const {
if (_lessThan)
{
// return true iff a1 < a2;
}
else
{
// return true iff a1 > a2;
}
}
};
You could then use it this way to sort in ascending order:
std::sort(std::begin(a), std::end(a), CompA(true));
And this way to sort in descending order:
std::sort(std::begin(a), std::end(a), CompA(false));
Another possibility, given your original LessA
comparator, is to use std::bind
to swap the order of the arguments to your custom comparator:
LessA comp;
using namespace std::placeholders;
std::sort(std::begin(v), std::end(v),
std::bind(&LessA::operator(), comp, _2, _1));