[英]How to create an auxiliary data structure to keep track of heap indices in a minheap for the decrease_key operation in c++
[英]creating minheap for structure in c++
#include <vector>
#include <algorithm>
struct doc {
double rank;
explicit doc(double r) : rank(r) {}
};
struct doc_rank_greater_than {
bool operator()(doc const& a, doc const& b) const {
return a.rank > b.rank;
}
};
int main() {
std::vector<doc> docvec;
docvec.push_back( doc(4) );
docvec.push_back( doc(3) );
docvec.push_back( doc(2) );
docvec.push_back( doc(1) );
std::make_heap(docvec.begin(),docvec.end(),doc_rank_greater_than());
std::cout << docvec.front().rank << '\n';
}
上面是使用自定义比较器为用户定义的数据类型创建最小堆的代码。 为什么我们使用 a.rank>b.rank 而不是 a.rank<b.rank 来创建最小堆?
正如std::make_heap
的文档所建议的那样, function 默认构造一个最大堆。 反转比较 function 使其构造一个最小堆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.