0

I have a structure whose objects are to be pushed into the 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();
    }
}

this code gives a compiler error that,

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

Any solutions to this, I'm usinf codeBlocks 16.01.

Thanks

Code Devil
  • 17
  • 7
  • A priority queue has to order the elements in the queue. To do that it needs to compare the elements. It's usually done using the less-than operator `<`. If you don't have a less-than operator overload (`operator<`) for your type then you will get that error. I suggest you [get a few good books to read](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) as they will teach you that and much more. – Some programmer dude Jun 11 '18 at 06:25

2 Answers2

1

You need to provide comparison operation for heapNode objects.

a) define operator< as member of heapNode

struct heapNode
{
  int i, j;
  double deltaQ;

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

b) you can pass functor object as comparator to priority_queue constructor

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

define functor

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

pass it to ctor of priority_queue

cmp c;
boost::heap::priority_queue<heapNode,boost::heap::compare<cmp>> maxHeap{c};
rafix07
  • 20,001
  • 3
  • 20
  • 33
0

In your heapNode structure you need to overload operator<.

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 would be a good start guide for you.

PVRT
  • 480
  • 4
  • 13