自定义sort函数第三个参数的规则
生活随笔
收集整理的這篇文章主要介紹了
自定义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()處理不了 >= 運算符。
轉載于:https://www.cnblogs.com/bearcarl/p/9222461.html
總結
以上是生活随笔為你收集整理的自定义sort函数第三个参数的规则的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 刷牙出血是什么原因 刷牙出血怎么办
- 下一篇: (详解)你应该知道的new操作符