# c++ stl question

3 replies to this topic

### #1ttigue

New Member

• Members
• 7 posts

Posted 01 December 2003 - 02:19 AM

I am using the c++ standard template library's priority_queue to implement an A* search. The priority_queue is made up of pointers to Path's.

class Path
{ int key;
.....

public:
bool operator < (Path & right);
bool operator > (Path & right);
};

......
bool Path::operator < (Path & right)
{  return key < right.key;  }


and the priority_queue is declared as

priority_queue <Path *, vector <Path *>, std::greater <Path *> > pq;


the problem is it is not sorting the paths by the key value - it is sorting them by the address that Path * points to. I am declaring the paths dynamically so I have to give the priority_queue pointers to the Path, but its sorting them by Path * not by the less than operator. any help would be appreciated - thanks

### #2Sfin

New Member

• Members
• 1 posts

Posted 01 December 2003 - 06:47 AM

What you need to do is create your own Comapre function. This example code should show you exactly how to do it:

http://www.cs.dal.ca...k/c++/pqComp.cc

P.S. This is not my code, I found it on the net, and don't take any credit for making it.

DevMaster Staff

• Members
• 1057 posts

Posted 01 December 2003 - 08:08 AM

mmhmm. you need to define your own comparison function object. SO, something like

struct key_comparison
{
bool operator () ( Path* p1, Path* p2 )
{
return (*p1) < (*p2);
}
};


of course you'll need to keep your greater/less then operator overloads in the Path class. Or you can have a GetKey() function and use those inside the key_comparison function object.

### #4ttigue

New Member

• Members
• 7 posts

Posted 01 December 2003 - 05:38 PM

That made it work. Thanks alot!

#### 1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users