Home > Software engineering >  c sort() function is not sorting my vector
c sort() function is not sorting my vector

Time:11-23

This is my code -

Problem: The sorting comparator function which I have written is not doing anything. the code gets executed, comparator function also runs, but it does not modify my vector. And I don't understand why.

Logic(which I have written):

  1. I have used region index as an index of my vector. For each region I have maintained a vector of (points, surname).

  2. Then, for each region, I have sorted my vector according to their points.

  3. then, I checked if there is no reputation in points on first position and second position, vis-a-vis for second and third position, that means we have clear winner, record them.

  4. Print the recorded winners.

#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;
}

CodePudding user response:

for (auto vec : cands) {

This create a copy of the elements in cands, not the actual element of cands itself.

Change your code to:

for (auto &vec : cands) {
  • Related