sort函数用重载运算符出错

来源:互联网 发布:日本军国主义知乎 编辑:程序博客网 时间:2024/06/02 01:57

在牛客网练习pat时感觉牛客网的检测严格些,之前在pat官网上提交通过的代码直接拷到牛客网有的会报错。

比如下面这一题。成绩排名的,官网链接https://www.patest.cn/contests/pat-b-practise/1004    牛客网https://www.nowcoder.com/pat/2/problem/4070

在官网上提交通过的代码如下

#include<stdio.h>#include<iostream>#include<algorithm>using namespace std;struct stu{    char name[100];    char no[100];    int score;    bool operator < (const stu &b) const{        if(score!=b.score) return score<b.score;    }}s[100];int main(){    int n;    while(scanf("%d",&n)!=EOF){        for(int i=0;i<n;i++){            scanf("%s%s%d",s[i].name,s[i].no,&s[i].score);        }        sort(s,s+n);        printf("%s %s\n",s[n-1].name,s[n-1].no);        printf("%s %s\n",s[0].name,s[0].no);    }    return 0;}
但是直接复制到牛客网报错如下

a.cpp:11:5: error: control may reach end of non-void function [-Werror,-Wret

然后我一直在想是不是函数return有错误,或者for循环i取值的问题。然后改了几次问题并没有解决。

后来想着不用重载试试,结果就对了。主要是把重载运算符的代码去了,重新给sort函数加了个比较函数。但是这是为什么呢?

修改后牛客网成功提交的代码

struct stu{    char name[100];    char no[100];    int score;}s[100];bool cmp(struct stu a, struct stu b){    return a.score<b.score;}


--------------------------------------------

重载在牛客网中正确提交如下:

bool operator < (const stu &b) const{    if(score!=b.score) return score<b.score;    else return false;}