题目
就是按列来排序,使用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; } ```
??正文结束??