700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > C++中sort函数从大到小排序

C++中sort函数从大到小排序

时间:2022-10-29 23:02:32

相关推荐

C++中sort函数从大到小排序

我们知道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;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。