|
20鱼币
我创建了一个结构,如下所示:
- struct Student{
- char id[25];
- int M;
- int m[15];
- int score=0;
- }s[1010];
复制代码
我想实现用sort()函数根据规则(规则1:分数降序输出。规则2:若分数相同则按他们考号的升序输出。)对s进行排序。
下面代码是我之前写的,发现输出的结果不尽人意 ,因为输入的数据过大,为了避免超时我又不得不使用scanf,但是用scanf输入std::string类型又不知道怎么输入(在网上也找了很久,没看到一个比较好解释怎么输入的),所以定义了字符串数组。但是定义了字符串数组后,sort排序的规则又不好编写 。
- bool cmp(Student a,Student b){
- if(a.score == b.score)
- return a.id < b.id;
- return a.score > b.score;
- }
- sort(s1, s1+N,cmp);
复制代码
来个大佬救救我吧
本帖最后由 柿子饼同学 于 2022-11-14 22:48 编辑
用 string 吧 , 方便很多 , 至于 cin 超时的问题请看 17, 18 行是如何解决的
原理就是原来 cin 和 scanf 在同一个流 , 然后要同步 , 所以就会很慢
这里直接解绑速度就好了 , 不过这时就不能 cin 和 scanf 混用了 , 不然会出错 , 当然 , cout 和 printf 也不能一起用
- #include <bits/stdc++.h>
- using namespace std;
- struct student{
- string id;
- int M;
- int m[15];
- int score;
- } s[1314];
- inline bool cmp(student a, student b){
- if(a.score == b.score) return a.id < b.id;
- return a.score > b.score;
- }
- int main(){
- ios::sync_with_stdio(0);
- cin.tie(0);
-
- return 0;
- }
复制代码
也可以用重载运算符 , 就不用写 cmp' 了
- struct student{
- string id;
- int M;
- int m[15];
- int score;
- bool operator < (const student & t) const {
- if(score == t.score) return id < t.id;
- return score > t.score;
- }
- } s[1314];
复制代码
|
最佳答案
查看完整内容
用 string 吧 , 方便很多 , 至于 cin 超时的问题请看 17, 18 行是如何解决的
原理就是原来 cin 和 scanf 在同一个流 , 然后要同步 , 所以就会很慢
这里直接解绑速度就好了 , 不过这时就不能 cin 和 scanf 混用了 , 不然会出错 , 当然 , cout 和 printf 也不能一起用
也可以用重载运算符 , 就不用写 cmp' 了
|