结构体排序
程序员文章站
2022-03-15 19:21:39
...
1,使用sort()
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
typedef struct example {
string name;
int score;
double money;
bool operator < (const example &x) const {
return score < x.score;
}
bool operator > (const example &x) const {
return money > x.money;
}
}Man;
Man arr[100];
void show_m(Man &s) {
cout << " || " << s.name << " " << s.score << " " << s.money << endl;
}
bool cmp1(Man &a, Man &b) {
return a.money < b.money;
}
int main() {
//data
int n = 0;
string s;
int sco;
double mon;
//input
cin >> n;
for (int i = 0; i < n; i++) {
cin >> s>>sco>>mon;
arr[i].name = s;
arr[i].score = sco;
arr[i].money = mon;
}
//cmp1,注意这里的小于对象和下面的并不相同
//sort(arr, arr + n, cmp1);
//重载操作符, < 前面小后面大 对应less
//sort(arr, arr + n);
//重载操作符, > 前大后小,对应greater
sort(arr, arr + n,greater<Man>());
//output
for_each(arr, arr + n, show_m);
system("pause");
return 0;
}
2.几个改进的地方
a.使用结构体内重载
b.尽量使用vector
c.学习使用for_each()遍历
d.标明各段的内容global variable
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
//structure
typedef struct example {
string name;
int score;
double money;
bool operator < (const example &x) const {
return score < x.score;
}
bool operator > (const example &x) const {
return money > x.money;
}
}Man;
//global variable
vector<Man> arr(100);
//functions
void show_m(Man &s) {
cout << " || " << s.name << " " << s.score << " " << s.money << endl;
}
int main() {
//data
int n = 0;
string s;
int sco;
double mon;
//input
cin >> n;
for (int i = 0; i < n; i++) {
cin >> s>>sco>>mon;
arr[i].name = s;
arr[i].score = sco;
arr[i].money = mon;
}
//重载操作符, > 前大后小,对应greater
sort(arr.begin(), arr.end(),greater<Man>());
//output
for_each(arr.begin(), arr.end(), show_m);
system("pause");
return 0;
}