【发布时间】:2013-08-21 17:18:27
【问题描述】:
在某处阅读以下语句:
额外的哈希表可用于快速删除 最小堆。
问题>如何结合priority_queue和unordered_map实现上面的思路?
#include <queue>
#include <unordered_map>
#include <iostream>
#include <list>
using namespace std;
struct Age
{
Age(int age) : m_age(age) {}
int m_age;
};
// Hash function for Age
class HashAge {
public:
const size_t operator()(const Age &a) const {
return hash<int>()(a.m_age);
}
};
struct AgeGreater
{
bool operator()(const Age& lhs, const Age& rhs) const {
return lhs.m_age < rhs.m_age;
}
};
int main()
{
priority_queue<Age, list<Age>, AgeGreater> min_heap; // doesn't work
//priority_queue<Age, vector<Age>, AgeGreater> min_heap;
// Is this the right way to do it?
unordered_map<Age, list<Age>::iterator, HashAge > hashTable;
}
问题>我无法完成以下工作:
priority_queue<Age, list<Age>, AgeGreater> min_heap; // doesn't work
我必须使用列表作为容器 b/c 列表的迭代器不受插入/删除的影响 (Iterator invalidation rules)
【问题讨论】:
-
我想我想知道您为什么要使用优先级队列来实现最小堆,因为我已经习惯了相反的方式。
-
你在哪里读到这个?
-
"一个额外的哈希表可用于在最小堆中快速删除。"虽然这可能是真的,也可能不是,但该声明并不是专门指
priority_queue和unordered_map,我严重怀疑它们是否可以以任何有效的方式一起使用,更不用说评论讨论的方式了。跨度> -
你是对的,这本书没有提到priority_queue或unordered_map。在这里,我只是想根据这个想法在c++中实现这个想法。