0

I'm trying to implement Dijkstra's Pathfinding Algorithm using the std::priority_queue. My Queue is of type Node* and I need it to prioritize based on a float gScore stored inside Node from smallest gScore to largest. I've read the documentation but I still don't understand how this can be achieved. Any ideas?

I don't understand what the type means by container_type(vector)

std::priority_queue<Node*> queue;

I greatly appreciate any help!

Bojangles
  • 3
  • 1

2 Answers2

1

You can create a class which will overload ()

class cmp
{ 
   public:
   bool operator()(const Node *a, const Node *b) const
   {
      return (a->gscore) > (b->gscore);
   }
 };

Then

 std::priority_queue<Node*,std::vector<Node*>,cmp);
Ajay
  • 18,086
  • 12
  • 59
  • 105
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
  • nice and simple explanation. Thank you very much! – Bojangles Jun 22 '16 at 04:59
  • @Bojangles Glad i could help.If this helped you can accept this as answer. – Gaurav Sehgal Jun 22 '16 at 05:00
  • Should be: `bool operator()(const Node *a, const Node *b) const` – Ajay Jun 22 '16 at 07:30
  • @Ajay Can you please point out why.Is it just good practice or something else. – Gaurav Sehgal Jun 22 '16 at 07:33
  • Good practice: Yes. You clarify the intent that operator is not going to change the contents. Reason: What if `const Node*` is the type for `priority_queue`? Non-const comparison operator simply wont compile. – Ajay Jun 22 '16 at 07:41
  • @Ajay Thanks a lot. – Gaurav Sehgal Jun 22 '16 at 07:43
  • Noticed one more thing that it will reverse the PQ. You probably need to use `<` operator. – Ajay Jun 22 '16 at 07:45
  • If i use `>` then the element with smallest `gscore` will have highest priority. – Gaurav Sehgal Jun 22 '16 at 07:47
  • No. Its the other way around. Most STL containers take `std::less` for comparison and are made with `<` as default comparison. PQ will enumerate with larger to smaller one with `<`. See sample: http://en.cppreference.com/w/cpp/container/priority_queue – Ajay Jun 22 '16 at 07:51
  • @GauravSehgal, Exactly that is my point. With `less`, higher value element will have higher priority (`3`). But with your custom comparator, which is `>` the element with LOWEST value gets higher priority (`1`). – Ajay Jun 22 '16 at 11:25
  • Oh well, yes. You are right. I didn't see that part in question! – Ajay Jun 22 '16 at 11:41
1

You will need a comparator function. I think it would be better to implement in a manner given below , rather than declaring a class for it.

auto comp = [] (Node* a,Node* b) -> bool { return a->gscore < b->gscore; };
priority_queue< Node*, std::vector<Node*>, decltype(comp) > foo(comp);
Shubham Jain
  • 1,864
  • 2
  • 14
  • 24