本文翻译自:Sorting a vector in descending order
Should I use 我应该用吗?
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
or 要么
std::sort(numbers.rbegin(), numbers.rend()); // note: reverse iterators
to sort a vector in descending order? 按降序对矢量进行排序? Are there any benefits or drawbacks with one approach or the other? 一种方法或另一种方法有任何好处或缺点吗?
#1楼
参考:https://stackoom.com/question/brps/按降序对矢量进行排序
#2楼
Actually, the first one is a bad idea. 实际上,第一个是个坏主意。 Use either the second one , or this: 使用第二个 ,或者:
struct greater
{
template<class T>
bool operator()(T const &a, T const &b) const { return a > b; }
};
std::sort(numbers.begin(), numbers.end(), greater());
That way your code won't silently break when someone decides numbers
should hold long
or long long
instead of int
. 这样,当有人决定numbers
应该持有多long
或多long long
而不是int
时,你的代码不会默默地破坏。
#3楼
What about this? 那这个呢?
std::sort(numbers.begin(), numbers.end());
std::reverse(numbers.begin(), numbers.end());
#4楼
使用c ++ 14,您可以这样做:
std::sort(numbers.begin(), numbers.end(), std::greater<>());
#5楼
您可以使用Lambda函数代替Mehrdad提出的仿函数。
sort(numbers.begin(), numbers.end(), [](const int a, const int b) {return a > b; });
#6楼
您可以使用第一个或尝试下面同样有效的代码
sort(&a[0], &a[n], greater<int>());