我正在尝试在 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
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] });
}
}
我本来希望插入对并且它们被排序了
您必须使用
map
而不是 unordered_map
,因为 unordered_map
是无序的。所以,你应该写
map<string, set<pair<int, string>, comp>> cuisinesMap;