gpt4 book ai didi

c++ - 即使没有指定自定义比较器, pair 的优先级队列如何工作?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:08:24 24 4
gpt4 key购买 nike

A std::priority_queue使用 std::vector作为默认容器(引用 this)。用于根据 std::vector<pair<int, int>> 中的第一个元素进行排序,我们需要定义自己的比较函数(引用 this)。这是我的理解。

现在,以下代码返回 k非空数组中出现频率最高的元素,复杂度为 O(NlogK):

class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
if(nums.empty())
return vector<int>();

unordered_map< int, int > hashMap;
for(int i=0; i<nums.size(); i++)
hashMap[nums[i]]++;

priority_queue< pair< int, int >> pq;
vector< int > result;
unordered_map< int, int >::iterator it=hashMap.begin();

for(it=hashMap.begin(); it!=hashMap.end(); it++) {
//the first one is frequency and the second one is the value
pq.push(make_pair(it->second, it->first));

//the peculiar implementation below is because we the code to be O(NlogK)
if(pq.size()>(hashMap.size()-k)) {
result.push_back(pq.top().second);
pq.pop();
}
}

return result;
}
};

此代码工作正常并被法官接受 - 但如何呢? std::priority_queue , 使用 std::vector<pair<int, int>>因为它的底层容器必须包含自定义比较函数,以便正确排序。那么,它是如何工作的呢?

最佳答案

坦率地说,它之所以有效,是因为它旨在这样做。

一些事情:

  • 一个std::priority_queue雇用 std::less<T> , 其中T是基础序列值类型,在未指定覆盖时作为默认比较器。
  • std::less<T>调用 operator <反对两个T争论,解决任何最适合和/或可用的问题。

因此,如果这按您希望的方式工作而没有对序列类型比较器进行特殊覆盖,则它一定意味着存在一个 operator <。对于 std::pair<int,int>将整个东西连接在一起。

确实有。检查 std::pair<T1,T2> 的文档,你会发现有一个 operator < 有效执行此操作的重载:

if (lhs.first < rhs.first)
return true;
else if (!(rhs.first < lhs.first))
return lhs.second < rhs.second
else
return false;

有关其工作原理的思维游戏示例留给读者思考。

关于c++ - 即使没有指定自定义比较器, pair<int,int> 的优先级队列如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45990622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com