Sign in to follow this  
Penguinzchaseme

Priority queues

Recommended Posts

Can someone show me a working example of a priority queue in C++ because I don't know the proper syntax. I need it to support a comparison function for a userdefined structure. thanx!

Share this post


Link to post
Share on other sites
SiCrane    11839
Here's an example:

struct SomeStruct {
int i;
float f;
};

struct Sorter {
bool operator()(const SomeStruct & lhs, const SomeStruct & rhs) {
if (lhs.i < rhs.i) return true;
if (lhs.i > rhs.i) return false;
if (rhs.f > rhs.f) return true;
return false;
}
};

int main(int, char **) {
std::priority_queue<SomeStruct, std::vector<SomeStruct>, Sorter> p_queue;
SomeStruct a = { 0, 0.0f };
SomeStruct b = { 1, 1.0f };
p_queue.push(a);
p_queue.push(b);

SomeStruct c = p_queue.top();

return 0;
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this