sort函数用重载运算符出错

在牛客网练习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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值