论RE

P5740 【深基7.例9】最厉害的学生

a_programmer @ 2024-08-08 12:59:20

#include <bits/stdc++.h>
using namespace std;
struct stu {
    string name;
    int chinese, math, english, total;
    friend istream & operator >> ( istream &in, stu &x ) {
        cin >> x.name >> x.chinese >> x.math >> x.english;
    }
    friend ostream & operator << ( ostream &out, stu &x ) {
        cout << x.name << " " << x.chinese << " " << x.math << " " << x.english << '\n';
    }
}a[1010];
int n, i, j;
int main() {
    cin >> n;
    for (i = 0; i < n; i++){
        cin >> a[i];
        a[i].total = a[i].chinese + a[i].math + a[i].english;
    }
    for(int i = n - 1;i > 0;i--) {
        bool b = true;
        for(int j = 0;j < i;j++) {
            if (a[j].total < a[j + 1].total){
                swap(a[j], a[j + 1]);
                b = false;
            }
        }
        if (b) break;
    }

    cout << a[0];
    return 0;
}

为什么开了O2后全RE?


by PengDave @ 2024-08-08 13:05:35

@a_programmer 你那两个友元成员函数没返回值


by ATZdhjeb @ 2024-08-08 13:06:02

您是否应该在重载的运算符里面 return cin / cout


by tangyiqi @ 2024-08-10 10:48:14

@a_programmer
用我的吧

#include <bits/stdc++.h>
using namespace std;
int n;
struct grade {
    int grade1,grade2,grade3;
    string name;
} a[1010];
int main() {
    scanf("%d",&n);
    for(int i = 0; i<n; i++) {
        cin>>a[i].name;
        scanf("%d%d%d",&a[i].grade1,&a[i].grade2,&a[i].grade3);
    }
    int ans1 = a[0].grade1+a[0].grade2+a[0].grade3,ans2 = 0;
    for(int i = 1; i<n; i++) {
        int z = a[i].grade1+a[i].grade2+a[i].grade3;
        if(z>ans1) {
            ans2 = i;
            ans1 = z;
        }
    }
    cout<<a[ans2].name<<" ";
    printf("%d %d %d",a[ans2].grade1,a[ans2].grade2,a[ans2].grade3);
    return 0;
}

求关,谢谢


|