如果您想根據您的LessA
比較確定的關係進行排序,只是傳遞的LessA
實例作爲第三個參數(和,因爲你正在使用C++ 11,喜歡全球std::begin()
和std::end()
功能):
std::sort(std::begin(a), std::end(a), LessA());
// ^^^^^^^
現在,如果你LessA()
表達<
關係,你需要根據相反的標準進行排序,你可以這樣做:
std::sort(std::begin(a), std::end(a),
[] (A const& a1, A const& a2))
{
return LessA()(a2, a1);
}
你可以做的另一件事就是讓你自定義的比較接受,決定了它應該如何執行比較參數:
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;
}
}
};
然後,您可以使用這種方式按升序進行排序:
std::sort(std::begin(a), std::end(a), CompA(true));
而且這種方式以按降序排列:
std::sort(std::begin(a), std::end(a), CompA(false));
另一種可能性,因爲你原來的LessA
比較,是用std::bind
交換的參數的順序您的自定義比較:
LessA comp;
using namespace std::placeholders;
std::sort(std::begin(v), std::end(v),
std::bind(&LessA::operator(), comp, _2, _1));
http://www.cplusplus.com/reference/algorithm/sort/ – 2013-05-14 18:26:54
拉姆達可能是您最好的選擇。 – Joel 2013-05-14 18:36:04