[英]std::sort descending order with operator overloading
I have an std::vector
of object for which I overloaded the <
operator. 我有一个
std::vector
对象,我重载了<
operator。
How can I use std::sort
to sort it in descending order (without needing to write my own Comparator)? 如何使用
std::sort
按降序对其进行排序(无需编写自己的Comparator)?
You could simply transpose the arguments to std::less
with the help of std::bind
: 你可以在
std::bind
的帮助下简单地将参数转换为std::less
:
using namespace std::placeholders;
std::sort(v.begin(), v.end(), std::bind(std::less<T>{}, _2, _1));
But I think it'd be much cleaner to simply write the equivalent short lambda, even if it goes against the constraint of not writing your own Comparator: 但是我认为简单地编写等效的短lambda会更加清晰,即使它违背了不编写自己的Comparator的限制:
std::sort(v.begin(), v.end(), [](T const& lhs, T const& rhs) { return rhs < lhs; });
std::sort(v.rbegin(), v.rend());
You can sort array by using std::sort
and then reverse it with std::reverse
. 您可以使用
std::sort
对数组进行std::sort
,然后使用std::sort
reverse将其std::reverse
。 This will sort in your desired way. 这将按您想要的方式排序。
std::sort(v.begin(), v.end());
std::reverse(v.begin(), v.end());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.