collision of same values in priority queue?

In case of two same values in the priority queue, how to make one particular value go on top as opposed to other? This is when the elements in the prio queue are structures.
For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// priority_queue::push/pop
#include <iostream>       // std::cout
#include <queue>          // std::priority_queue

struct node {
    int info;
    int cost;
    bool operator<(const node& other)const
    { return cost > other.cost; }
};

int main ()
{
  std::priority_queue<node> mypq;
  
  node a;
  
  a.info=1;
  a.cost=10;
  mypq.push(a);
  
   a.info=4;
  a.cost=4;
  mypq.push(a);
  
   a.info=3;
  a.cost=20;
  mypq.push(a);
  
   a.info=2;
  a.cost=4;
  mypq.push(a);
  

  std::cout << "Popping out elements...";
  while (!mypq.empty())
  {
      a=mypq.top();
     std::cout << a.info<<","<<a.cost<<"\t";
     mypq.pop();
  }
  std::cout << '\n';

  return 0;
}


I have a priority queue set up to return smallest element at the top.(reverse ordering as opposed to standard). I have overloaded < operator for this.
Now when there are 2 entries in the queue with same key value(value on which priority queue is sorted), the element that was inserted first always comes out first. How to decide which of the two colliding elements to pop based on some other criterion?

When I enter (4,4) and (2,4), since (4,4) goes in first, it comes out first before (2,4). When "a.cost" values are same, I want to compare 2 and 4, i.e.
" a.info " values and then make smaller one come on top.

Any help will be appreciated.
Change your comparison function so that if the costs are the same you compare info values, otherwise you return the same value as you do now.
Okay. I did this. And it worked!!

1
2
3
4
5

 bool operator<(const node& other)const
    {   if(cost == other.cost)
            return info > other.info;
        return cost > other.cost; }

Thanks :)
Last edited on
Topic archived. No new replies allowed.