我试图通过对我自己的布尔函数使用STL排序来对vector<pair<int, int>>
进行排序。
#include <bits/stdc++.h>
using namespace std;
bool comp(pair<int, int> u1, pair<int, int> u2){
if(u1.first != u2.first) return u1.first < u2.first;
return u2.second > u2.second;
}
int main(void){
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int univs, day, pay, max_income = 0, spent = 0;
vector<pair<int, int>> day_pay;
cin >> univs;
for(int u = 0; u < univs; u++){
cin >> pay >> day;
day_pay.push_back(make_pair(day, pay));
}
for(int i = 0; i < univs; i++) cout << day_pay[i].first << " " << day_pay[i].second << endl;
cout << endl;
sort(day_pay.begin(), day_pay.end(), comp);
for(int i = 0; i < univs; i++) cout << day_pay[i].first << " " << day_pay[i].second << endl;
for(int u = 0; u < univs; u++){
if(day_pay[u].first <= spent) continue;
max_income += day_pay[u].second;
spent++;
}
cout << max_income;
}
这是测试用例:
4
50 2
10 1
20 2
30 1
我想将此案例排序为
30 1
10 1
50 2
20 2
我应该怎么做才能解决这个问题?
答案 0 :(得分:0)
查看您的comp函数。 if之后的行:
return u2.second > u2.second;
不应该这样:
return u1.second > u2.second
答案 1 :(得分:0)
行
return u2.second > u2.second;
是可疑的。您很可能是故意的
return u1.second > u2.second;
答案 2 :(得分:0)
我认为这很适合排序,请根据您的问题进行修改。 (PS:这是C ++ 14,不适用于C ++ 11。)
#include <iostream>
#include <vector>
#include <utility>
int32_t main() {
int t;
std::cin >> t;
std::vector<std::pair<int, int>> v(t);
for(auto &i : v)
std::cin >> i.first >> i.second;
std::sort(v.begin(), v.end(), [](const auto &a, const auto &b) {
return (a.second != b.second) ? (a.second < b.second) : (a.first > b.first);
});
for(auto &i : v)
std::cout << i.first << " " << i.second << std::endl;
return 0;
}