我们知道C++中有一个函数 sort()
它默认是从小到大排序,那么如何从大到小排呢?
一种方法是使用greater<int>()
,如下例子
#include <iostream>#include <vector>#include <algorithm>using namespace std;int main() {vector<int> nums = {3, 2, 4, 1, 5};sort(nums.begin(), nums.end(), greater<int>());for (auto x: nums) cout << x << ' ';return 0;}
再一种是自定义比较函数,将大的排到前面。如下
#include <iostream>#include <vector>#include <algorithm>using namespace std;bool cmp(int a, int b) {return a > b;}int main() {vector<int> nums = {3, 2, 4, 1, 5};sort(nums.begin(), nums.end(), cmp);for (auto x: nums) cout << x << ' ';return 0;}