1028 List Sorting

本文探讨了在C++中使用字符串进行排序的方法,包括如何利用strcmp()函数比较字符串,以及如何通过优化I/O操作提升cin和cout的效率。通过实例展示了不同排序条件下的比较函数实现,并提供了完整的代码示例。

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

题目

题目链接

就是按列来排序,使用sort()函数就是调用不同的比较函数就行了,比较字符串本来自己写得蛮复杂的,后来发现有一个函数可以解决.

知识点

是处理c中字符串(即char数组)的一个头文件,所以在使用里面的函数前,使用c++string必须通过c_str()函数转为c语言中的string.这里面有很多有用的函数,以后会总结一下. ## strcmp() 这个函数会按Ascll自左向右比较大小,以前的时候还不知道,返回值是这样的 >当s1<s2时,返回为负数; > >当s1==s2时,返回值= 0; > >当s1>s2时,返回正数。 ## cin,cout速度慢 cin,cout用起来很方便,但速度低于scanf和printf,但是有解决办法,解决办法就是加一句代码 ```cpp int main() { ios::sync_with_stdio(false); int n,c; return 0; } ``` # 代码 ```cpp #include #include #include #include using namespace std; struct student { string id; string name; int score; }; bool com1(student a,student b) { return stoi(a.id.c_str())<stoi(b.id.c_str()); } bool com2(student a,student b) { if(strcmp(a.name.c_str(), b.name.c_str()) == 0) return stoi(a.id) < stoi(b.id); return strcmp(a.name.c_str(), b.name.c_str()) <= 0; } bool com3(student a,student b) { return a.score==b.score?com1(a,b):a.score<b.score; } int main() { ios::sync_with_stdio(false); int n,c; cin>>n>>c; vector result(n); for(int i=0; i<n; i++) { cin>>result[i].id>>result[i].name>>result[i].score; } if(c==1) { sort(result.begin(),result.end(),com1); } else if(c==2) { sort(result.begin(),result.end(),com2); } else { sort(result.begin(),result.end(),com3); } for(int i=0; i<result.size(); i++) { cout<<result[i].id<<" "<<result[i].name<<" "<<result[i].score<<"\n"; } return 0; } ```
??正文结束??
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值