1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 关于sort函数从大到小排序的方法(实用)

关于sort函数从大到小排序的方法(实用)

时间:2020-10-19 15:24:51

相关推荐

关于sort函数从大到小排序的方法(实用)

关于sort函数从大到小排序的方法(实用)

初始情况:

#include<iostream>#include<algorithm>using namespace std;int main(){int a[5] = {5,1,2,4,3 };sort(a, a + 5);for (int i = 0; i < 5; i++)cout << a[i]<<" ";return 0;}

第一种:是使用greater()

#include<iostream>#include<algorithm>using namespace std;int main(){int a[5] = {5,1,2,4,3 };sort(a, a + 5,greater<int>());for (int i = 0; i < 5; i++)cout << a[i]<<" ";return 0;}

第二种:自己创建一个比较函数,

#include<iostream>#include<algorithm>using namespace std;int yang(int a, int b);int main(){int a[5] = {5,1,2,4,3 };sort(a, a + 5,yang);for (int i = 0; i < 5; i++)cout << a[i]<<" ";return 0;}int yang(int a, int b){return a > b;}

将两种方法汇到一起:

#include<iostream>#include<algorithm>using namespace std;int yang(int a, int b);int main(){int a[5] = {5,1,2,4,3 };int b[5] = {5,1,2,4,3 };sort(b, b + 5,greater<int>());sort(a, a + 5,yang);for (int i = 0; i < 5; i++)//输出自己创建比较函数的值cout << a[i]<<" ";cout <<endl;for (int i = 0; i < 5; i++)//输出greater的值cout << b[i] << " ";return 0;}int yang(int a, int b){return a > b;}

运行代码结果:

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