法一:cmp函数
代码实现
#include<iostream>
#include<algorithm>
using namespace std;
int cmp(int a, int b)
{
return a > b;
}
int main()
{
int num[5] = {1, 2, 3, 4, 5};
sort(num, num + 5, cmp);
for ( int i = 0; i < 5; i ++ ) cout << num[i] << " ";
cout << endl;
return 0;
}
运行结果
法二:结构体重载大于号
注:需要将大于号重载给结构体中排序的关键变量
代码实现
#include<iostream>
#include<algorithm>
using namespace std;
struct Edge{
int a, b;
bool operator< (const Edge &W)const{
return a > W.a;
}
}edges[5];
int main()
{
for ( int i = 0; i < 5; i ++ ) edges[i].a = edges[i].b = i + 1;
sort(edges, edges + 5);
for ( int i = 0; i < 5; i ++ ) cout << edges[i].a << " " << edges[i].b << endl;
cout << endl;
return 0;
}
运行结果
greater()参数
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int num[5] = {1, 2, 3, 4, 5};
sort(num, num + 5, greater<int>());
for ( int i = 0; i < 5; i ++ ) cout << num[i] << " ";
cout << endl;
return 0;
}