PDA

View Full Version : c++ stl question


ttigue
11-30-2003, 06:19 PM
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

Sfin
11-30-2003, 10:47 PM
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/~sedgwick/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.

bladder
12-01-2003, 12: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.

ttigue
12-01-2003, 09:38 AM
That made it work. Thanks alot!