使用 C++ 中的自定义比较器对 <int, string> 对进行排序

问题描述 投票:0回答:1

我正在尝试在 C++ 中创建一组对,并使用自定义比较器对其进行有效排序。我的要求是:

主排序:根据对的整数元素进行降序排列。 二级排序(如果整数相等):根据该对的字符串元素升序排列。

这是我的自定义比较器函数:

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

我在 FoodRatings 构造函数中构造 unordered_map, comp>> 时使用此 comp 函数:

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] });
  }
}

我本来希望插入对并且它们被排序了

stl set unordered-map
1个回答
0
投票

您必须使用

map
而不是
unordered_map
,因为
unordered_map
是无序的。所以,你应该写

map<string, set<pair<int, string>, comp>> cuisinesMap;
© www.soinside.com 2019 - 2024. All rights reserved.