使用指定的順序對序列容器進行排序

如果容器中的值已經過載某些運算子,則 std::sort 可以與專門的仿函式一起使用,以升序或降序排序:

Version >= C++ 11

#include <vector>
#include <algorithm>
#include <functional>

std::vector<int> v = {5,1,2,4,3};

//sort in ascending order (1,2,3,4,5)
std::sort(v.begin(), v.end(), std::less<int>());

// Or just:
std::sort(v.begin(), v.end());

//sort in descending order (5,4,3,2,1)
std::sort(v.begin(), v.end(), std::greater<int>());

//Or just:
std::sort(v.rbegin(), v.rend());

Version >= C++ 14

在 C++ 14 中,我們不需要為比較函式物件提供模板引數,而是讓物件根據傳入的內容進行推導:

std::sort(v.begin(), v.end(), std::less<>());     // ascending order
std::sort(v.begin(), v.end(), std::greater<>());  // descending order