本意思路:运用结构体sort进行排序,这里可以使用运算符重载或写一个函数,我选用的是运算符重载。
底层运用的是运算符,所以我们可以重载运算符。
重载运算符模板:
bool operator < (node a, node b) {
return a > b;
}//将 < 变成 > ,但要注意一点, 传入的参数只能是自定义类型
以下下代码会报错:
bool operator < (int a, int b) {
return a > b;
}//错误
下面看代码:
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 5005;
int n;
struct node {
int h, m, s;
}a[N];
bool operator < (node a, node b) {//重载小于运算符
return a.h < b.h || a.h == b.h && a.m < b.m || a.h == b.h && a.m == b.m && a.s < b.s;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
cin >> n;
for (int i = 1; i <= n; i ++)
cin >> a[i].h >> a[i].m >> a[i].s;
sort (a + 1, a + 1 + n);
for (int i = 1; i <= n; i ++)
cout << a[i].h << " " << a[i].m << " " << a[i].s << endl;
return 0;
}
制作不易,给个赞呗!