Skip to main content
gamedev.net
🔒 Locked

[STL] priority_queue comparison function

Started by gimp Feb 25, 2003 at 3:29 AM 0 replies 450+ views
Original Post
gimp
gimp
I have a bunch of pointers in a priority_queue. They are threads in a scheduler. I can sort threads with a function that determines next execution time, by default however the priority queue will sort the threads based on their pointers memory address, not terribly useful So I looked at the comparison function and couldn''t quite work out how to make it work. I kind of expected it to work the way a comparison function on std::sort() would work but I can''t seem to get it to work. Assuming my comparison function looks like this(and it''s probably wrong)... bool ThreadOrder (const CThread* a_First, const CThread* a_Second); What does a constructor look like? I looks like that if I want to specify a comparison function I also need to specify the base container type. Something like: std:riority_queue< , ThreadOrder> Threads; Would anyone like to correct my code grammer or perhaps let me know where I''m going wrong? Many thanks, Chris Brodie http:\\fourth.flipcode.com
Chris Brodie
janharal
janharal
You should find the information you need at SGI''s website (better info than MSDN):

http://www.sgi.com/tech/stl/priority_queue.html

The following should work:

#include <queue>
#include <iostream>

class MyClass {
public:
int m_value;
MyClass(int value) {
m_value = value;
}
};

class MyCompare {
public:
bool operator () (const MyClass* left, const MyClass* right) {
return left->m_value < right->m_value;
}
};

int main() {
std:riority_queue, MyCompare > myQueue;

myQueue.push(new MyClass(3));
myQueue.push(new MyClass(2));
myQueue.push(new MyClass(6));
myQueue.push(new MyClass(4));

std::cout << "Greatest: " << myQueue.top()->m_value << std::endl;

return 0;
}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.