本文介紹了按降序對向量進行排序的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我應該使用
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
或
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?
推薦答案
實際上,第一個是個壞主意.使用第二個,或者這樣:
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());
這樣,當有人決定 numbers
應該包含 long
或 long long
而不是 int代碼>.
That way your code won't silently break when someone decides numbers
should hold long
or long long
instead of int
.
這篇關于按降序對向量進行排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!