c++ - Sort objects in descending order when the < comparator is defined? -
i have class a
, <
comparator. how can use them sort array of a
in descending order?
class { ... }; class lessa { bool operator()(const a& a1, const a& a2) const { ... } } vector<a> v; sort(v.begin(), v.end(), ???);
i suppose should replace ???
based on lessa
, can't figure out should go in there. thought of using lambda function, looking shorter.
if want sort according relation defined lessa
comparator, pass instance of lessa
third argument (and, since using c++11, prefer global std::begin()
, std::end()
functions):
std::sort(std::begin(a), std::end(a), lessa()); // ^^^^^^^
now if lessa()
expresses <
relation , want sort according opposite criterion, do:
std::sort(std::begin(a), std::end(a), [] (a const& a1, const& a2)) { return lessa()(a2, a1); }
another thing let custom comparator accept argument determines how should perform 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 use way sort in ascending order:
std::sort(std::begin(a), std::end(a), compa(true));
and way sort in descending order:
std::sort(std::begin(a), std::end(a), compa(false));
another possibility, given original lessa
comparator, use std::bind
swap order of arguments custom comparator:
lessa comp; using namespace std::placeholders; std::sort(std::begin(v), std::end(v), std::bind(&lessa::operator(), comp, _2, _1));
Comments
Post a Comment