yousef sayed
yousef sayed

Reputation: 3

Sorting set of <int, string> pairs with custom comparator in C++

I'm trying to create a set of pair<int, string> in C++ and sort it efficiently using a custom comparator. My requirements are:

Primary sort: Descending order based on the integer element of the pair. Secondary sort (if equal integers): Ascending order based on the string element of the pair.

Here's my custom comparator function:

struct comp {
  bool operator()(const pair<int, string> &a, const pair<int, string> &b) {
    if (a.first != b.first) return a.first > b.first; // Changed for descending order
    return a.second < b.second; // Ascending order for secondary sort
  }
};

I'm using this comp function when constructing the unordered_map<string, set<pair<int, string>, comp>> in the FoodRatings constructor:

unordered_map<string, set<pair<int, string>, comp>> cuisinesMap;

FoodRatings(vector<string>& foods, vector<string>& cuisines, vector<int>& ratings) {
  int n = foods.size();
  for (int i = 0; i < n; i++) {
    cuisinesMap[cuisines[i]].insert({ ratings[i], foods[i] });
  }
}
and why can't I call it by reference 
void changeRating(string food, int newRating) {
        for(auto &i : cuisinesMap)
        {

            for(pair<int,string> &j : i.second) // here
            {
                if(j.second == food)
                {
                    j.first = newRating;
                    cuisinesMap[i.first].insert(j);
                }
            }
        }
    }

I was expecting to insert pairs and they get sorted

Upvotes: 0

Views: 254

Answers (1)

Nathan Jiang
Nathan Jiang

Reputation: 132

You must use a map not an unordered_map because unordered_map's are unordered. So, you should write

map<string, set<pair<int, string>, comp>> cuisinesMap;

Upvotes: 0

Related Questions