在boost :: heap :: priority_queue中推送结构对象时出错

时间:2018-06-11 06:22:34

标签: c++ c++11 boost heap priority-queue

我有一个结构,其对象将被推入boost::heap::priority_queue

typedef struct
{
  int i, j;
  double deltaQ;

} heapNode;

int main()
{
    double a[] = {0.03, 0.01, 0.04, 0.02, 0.05};
    heapNode node;

    boost::heap::priority_queue<heapNode> maxHeap;
    for(int  i = 0; i < 5; i++)
    {
        node.deltaQ = a[i];
        node.i = i;
        node.j = i;
        maxHeap.push(node);//error
    }

    for(int i = 0; i < 5; i++)
    {
        node = maxHeap.top();
        cout << node.deltaQ << " " << node.i << " " << node.j;
        cout << "\n";
        maxHeap.pop();
    }
}

此代码给出了编译器错误,

error: no match for 'operator<' (operand types are 'const heapNode' and 'const heapNode')|

对此有任何解决方案,我使用codeBlocks 16.01。

由于

2 个答案:

答案 0 :(得分:1)

您需要为heapNode个对象提供比较操作。

a)将operator<定义为heapNode

的成员
struct heapNode
{
  int i, j;
  double deltaQ;

  bool operator<(const heapNode& theOther) const {
      // your comparison operation
    return this->deltaQ < theOther.deltaQ;
  }
};

b)您可以将functor对象作为比较器传递给priority_queue构造函数

  

explicit priority_queue(value_compare const & = value_compare());

定义仿函数

struct cmp {
   bool operator () (const heapNode& lhs, const heapNode& rhs) const {
     return lhs.deltaQ < rhs.deltaQ;
   }
};

将其传递给priority_queue的ctor

cmp c;
boost::heap::priority_queue<heapNode,boost::heap::compare<cmp>> maxHeap{c};

答案 1 :(得分:0)

在heapNode结构中,您需要重载运算符&lt;

struct HeapNode
{
  int i, j;
  double deltaQ;
  bool operator<(const HeapNode& other)
  {
     *return true if current HeapNode is less than other, else false*
  };

} heapNode;

http://en.cppreference.com/w/cpp/language/operators对您来说是一个很好的入门指南。