C++ 按指定的顺序对序列容器进行排序

示例

如果容器中的值已经重载了某些运算符,则std::sort可以将其与专用函子一起使用,以升序或降序排序:

C ++ 11
#include <vector>
#include <algorithm>
#include <functional>

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

//升序排序(1,2,3,4,5)
std::sort(v.begin(), v.end(), std::less<int>());

// 要不就:
std::sort(v.begin(), v.end());

//降序排列(5,4,3,2,1)
std::sort(v.begin(), v.end(), std::greater<int>());

//要不就:
std::sort(v.rbegin(), v.rend());
C ++ 14

在C ++ 14中,我们不需要为比较函数对象提供模板参数,而是让对象根据传入的内容推论得出:

std::sort(v.begin(), v.end(), std::less<>());     // 升序
std::sort(v.begin(), v.end(), std::greater<>());  // 降序排列