Fork me on GitHub

C++ vector排序实例

话不多说,直接上c++代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//
// Created by chengw on 2019-05-09.
//
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

struct student {
string name;
int score;
};

bool More(const student &a, const student &b){
return a.score > b.score;
}

bool Less(const student &a, const student &b){
return a.score < b.score;
}

int main(){
int N,type;
cout << "Please input nums and order:(1-increase;0-decrease)" << endl;
while (cin >> N >> type){
vector<student> s(N);
cout << "name:" << " score:" << endl;
for(int i=0; i < N; i++){
cin >> s[i].name >> s[i].score;
}

cout << "after sort:" << endl;
if(type == 0)
stable_sort(s.begin(), s.end(), More); //稳定排序
else
stable_sort(s.begin(), s.end(), Less);

for(int i = 0; i < N; i ++){
cout << s[i].name << " " << s[i].score << endl;
}
}
return 0;
}

编译后,执行输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Please input nums and order:(0-increase;1-decrease)
5 1
name: score:
a 98
b 78
c 99
d 100
e 67

after sort:
e 67
b 78
a 98
c 99
d 100
您的鼓励是我持之以恒的动力