[英]C++ min heap with user-defined type
I am trying to implement a min heap in c++ for a struct type that I created. 我试图在c ++中为我创建的结构类型实现最小堆。 I created a vector of the type, but it crashed when I used make_heap on it, which is understandable because it doesn't know how to compare the items in the heap.
我创建了一个类型的向量,但是当我在其上使用make_heap时崩溃了,这是可以理解的,因为它不知道如何比较堆中的项目。 How do I create a min-heap (that is, the top element is always the smallest one in the heap) for a struct type?
如何为结构类型创建最小堆(即顶部元素始终是堆中的最小元素)?
The struct is below: 结构如下:
struct DOC{
int docid;
double rank;
};
I want to compare the DOC structures using the rank member. 我想使用rank成员比较DOC结构。 How would I do this?
我该怎么做?
I tried using a priority queue with a comparator class, but that also crashed, and it also seems silly to use a data structure which uses a heap as its underlying basis when what I really need is a heap anyway. 我尝试使用带有比较器类的优先级队列,但是也崩溃了,使用数据结构似乎很愚蠢,当我真正需要的是堆时,使用堆作为其底层基础。
Thank you very much, bsg 非常感谢,bsg
Simply create your own "functor" for the comparison. 只需创建自己的“仿函数”进行比较。 Since you want a "min heap" your comparison function should behave like the greater than operator:
由于您需要“最小堆”,因此比较函数应该像大于运算符一样:
#include <iostream>
#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';
}
It's important that you always use the same comparison function in further heap operations. 在进一步的堆操作中始终使用相同的比较函数非常重要。
Add a comparison operator: 添加比较运算符:
struct DOC{
int docid;
double rank;
bool operator<( const DOC & d ) const {
return rank < d.rank;
}
};
Structures can almost always usefully have a constructor, so I would also add: 结构几乎总是有用的有一个构造函数,所以我还要添加:
DOC( int i, double r ) : docid(i), rank(r) {]
to the struct as well. 结构也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.