這是我的代碼 -
問題:我撰寫的排序比較器函式沒有做任何事情。代碼被執行,比較器函式也會運行,但它不會修改我的向量。我不明白為什么。
邏輯(我寫過):
我使用區域索引作為我的向量的索引。對于每個區域,我都維護了一個向量(點,姓氏)。
然后,對于每個區域,我根據他們的點對我的向量進行了排序。
然后,我檢查了第一名和第二名的積分是否沒有聲譽,相對于第二名和第三名,這意味著我們有明確的贏家,記錄下來。
列印記錄的獲勝者。
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main() {
int participants, regions;
cin >> participants >> regions;
vector<vector<pair<int, string>>> cands(regions);
string surname;
int region, points;
for (int i{0}; i<participants; i ) {
cin >> surname >> region >> points;
cands[region-1].push_back({points, surname});
}
for (auto vec : cands) {
sort(vec.rbegin(), vec.rend(), [](pair<int, string>& x, pair<int, string>& y) {
return x.first > y.first;
});
}
// for (auto vec : cands) {
// for (auto ele : vec) cout << ele.first << " " << ele.second << endl;
// cout << endl;
// }
vector<pair<string, string>> teams;
for (auto vec : cands) {
if (vec[0].first == vec[1].first) teams.push_back({"?", ""});
else {
if (vec.size() > 2) {
if (vec[1].first == vec[2].first) teams.push_back({"?", ""});
else teams.push_back({vec[0].second, vec[1].second});
} else teams.push_back({vec[0].second, vec[1].second});
}
}
for (auto ele : teams) cout << ele.first << " " << ele.second << endl;
return 0;
}
uj5u.com熱心網友回復:
for (auto vec : cands) {
這會創建 中元素的副本cands,而不是其cands本身的實際元素。
將您的代碼更改為:
for (auto &vec : cands) {
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/363642.html
