C++排序函数cmp()总结&解决成绩按条件排序问题

本文深入探讨了C++中cmp函数的应用,包括基本数据类型和结构体类型的排序技巧。通过实例,详细讲解了如何自定义排序规则,并对比了值传递与引用传递的效率差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++中cmp()函数用途很多,特此总结:

  1. 一般数据类型的排序:
#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);//sort()函数包含在头文件<algorithm>中
   for (int i = 0; i < 5; i++) {
   	cout << a[i] << " ";
   }
   return 0;
}

注意:当sort中第三个参数cmp默认是从小到大排序的

  1. 结构体类型的比较
    例题:

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;
}
  1. 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);//sort()函数包含在头文件<algorithm>中
   for (int i = 0; i < 5; i++) {
   	cout << a[i] << " ";
   }
   return 0;
}

值传递函数将自动产生临时变量用于复制参数,效率较低
引用传递仅借用函数名不产生临时对象,因此效率比值传递高
引用传递”有可能改变参数,const修饰可以解决这个问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值