自定义sort函数第三个参数的规则

先贴错误代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;

struct stu {
    long id;
    int de;
    int cai;
    int total;
};

vector <stu> a1, a2, a3, a4;

bool cmp_1(const stu& a, const stu& b) {
    return (a.total > b.total || (a.total == b.total && a.de >= b.de)); //注意这句话
}

int main() {
    freopen("E:/VSproject/hdu/hdu1041/Debug/in.txt", "r", stdin);
    int n, l, h, sum = 0;
    cin >> n >> l >> h;
    stu temp;
    for(int i = 0; i < n; i++) {
        cin >> temp.id >> temp.de >> temp.cai;
        temp.total = temp.de + temp.cai;
        //分配
        if(temp.de >= h && temp.cai >= h) 
            a1.push_back(temp), sum++;
        else if(temp.de >= h && temp.cai >= l && temp.cai < h)
            a2.push_back(temp), sum++;
        else if(temp.de >= temp.cai && temp.cai >= l)
            a3.push_back(temp), sum++;
        else if(temp.de >= l && temp.cai >= l) 
            a4.push_back(temp), sum++;
    }
    // 排序
    sort(a1.begin(), a1.end(), cmp_1);
    sort(a2.begin(), a2.end(), cmp_1);
    sort(a3.begin(), a3.end(), cmp_1);
    sort(a4.begin(), a4.end(), cmp_1);
    //显示
    cout << sum << endl;
    for(int i = 0; i < a1.size(); i++) 
        printf("%ld %d %d\n", a1[i].id, a1[i].de, a1[i].cai);
    for(int i = 0; i < a2.size(); i++) 
        printf("%ld %d %d\n", a2[i].id, a2[i].de, a2[i].cai);
    for(int i = 0; i < a3.size(); i++) 
        printf("%ld %d %d\n", a3[i].id, a3[i].de, a3[i].cai);
    for(int i = 0; i < a4.size(); i++) 
        printf("%ld %d %d\n", a4[i].id, a4[i].de, a4[i].cai);
}

主要需要注意的是这句

bool cmp_1(const stu& a, const stu& b) {
    return (a.total > b.total || (a.total == b.total && a.de >= b.de)); //注意这句话
}
这是自定义的比较函数,可编译通过,但是会产生运行错误。
更改的方法:
bool cmp_1(const stu& a, const stu& b) {
    return (a.total > b.total || (a.total == b.total && a.de > b.de));
}
这是在 >= 与 > 可互换的情况下的更改
如果要保持原语义完全不变,可改为如下:
呃呃,没弄出来,换了好多个句子,都不成,是不是它会自动优化我的代码导致最后代码都是一样,但STL的sort()又处理不了 >= 的运算符造成的?
等有时间探究一下。
初步猜测是sort()处理不了 >= 运算符。

猜你喜欢

转载自www.cnblogs.com/bearcarl/p/9222461.html