C++中cmp()函数用途很多,特此总结:
- 一般数据类型的排序:
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a, int b) {
return a > b;
}
int main() {
int a[5] = { 1,5,2,4,3 };
sort(a, a + 5,cmp);
for (int i = 0; i < 5; i++) {
cout << a[i] << " ";
}
return 0;
}
注意:当sort中第三个参数cmp默认是从小到大排序的
- 结构体类型的比较
例题:
Every semester, our teacher makes a ranklist based on grades of
students. Now he asks you to help making the ranklist.Every student
has two subjects in this semester, mathematics and English.
Here comes the rules of the ranklist. First , sort the sum of grades
of all subjects from high to low. If two students have the same
grades, then rank the student whose mathematics’s grade higher in the
first place. Otherwise, we do nothing when we make the ranklist.
Input For each test case, the first line contains a single integer
N(1<=N<=500) which is the number of students. Following the first
line, there are N lines of the students’ grades. Each line has two
single integer a,b(0<=a,b<=100) seperated by a blank. The first is
mathematics, and the second is English. Output For each test case,
output the ranklist which has N lines. Each line has two single
integers which are the ith(1<=i<=N) rank students’ grades. The first
is mathematics,and the second is English, seperate by a blank. There
is no leading or trailing spaces.
代码1:常规cmp()代码:
#include<iostream>
#include<algorithm>
using namespace std;
struct score {
int math, eng;
}a[50];
bool cmp(score a, score b) {
if (a.math + a.eng != b.math + b.eng) return a.math + a.eng > b.math + b.eng;
else return a.math > b.math;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i].math >> a[i].eng;
}
sort(a, a + n, cmp);
for (int i = 0; i < n; i++) {
cout << a[i].math << " " << a[i].eng << endl;
}
return 0;
}
- cmp函数中&的用法:
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(const int &a,const int &b){
return a > b;
}
int main() {
int a[5] = { 1,5,2,4,3 };
sort(a, a + 5,cmp);
for (int i = 0; i < 5; i++) {
cout << a[i] << " ";
}
return 0;
}
值传递函数将自动产生临时变量用于复制参数,效率较低
引用传递仅借用函数名不产生临时对象,因此效率比值传递高
引用传递”有可能改变参数,const修饰可以解决这个问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)