Page 1 of 1

STL priority queue

Posted: Thu Dec 16, 2004 11:36 pm
by Mohammad Mahmudur Rahman
suppose I have a structure as follwos -
[cpp]
struct test_
{
int id,val1,val2;
};
[/cpp]

Then a STL priority queue with type test_ is created. Now if I want to set val1 as the key of the priority queue, I guess I need to write my own comparison function overriding the default COMP. Now can someone please give me an example of such a custom compare function & how the priority_queue is to be declared then? Thanks in advance.

Posted: Fri Dec 17, 2004 2:09 am
by Krzysztof Duleba
No, you just have to add operator< to test_ class. For instance:
[cpp]struct test_{
int id, val1, val2;
bool operator<(const test_ &t)const{
if(val1 != t.val1)return (val1 < t.val1);
else return (val2 < t.val2);
}
}

int main(){
priority_queue<test_> q;
}

[/cpp]Note that priority_queue will return by default the biggest element when top() is called.
If you want to use a custom binary bool function object, then you should do it this way:
[cpp]
priority_queue<test_, vector<test_>, cmp_object> q;
[/cpp]
For instance, to get the smallest element in queue, use greater<type_> object:
[cpp]
priority_queue<test_, vector<test_>, greater<test_> > q;
[/cpp]
In this case you have to define operator> in class test_.

Posted: Fri Dec 17, 2004 2:12 am
by UFP2161
[cpp]struct Foo
{
int key;
int value;

bool operator<(const Foo& foo) const
{
return key < foo.key;
}
};

priority_queue<Foo> myPriorityQueue;[/cpp]

There are many other ones to do it, but usually it is just best to override the less than operator, which is the default for any ordered STL container.

Posted: Sat Dec 18, 2004 8:19 pm
by Mohammad Mahmudur Rahman
Many thanks to both of you for help. I have finally been made it to work.

Posted: Mon Jan 31, 2005 3:57 pm
by sqm
I wonder if someone could help me:
I have priority_queue of pointers to struct:

struct type{
int val;
};

priority_queue<type*>Q;

How can I overload operator?

Posted: Tue Feb 01, 2005 5:17 pm
by Krzysztof Duleba
It's quite straightforward. You must provide a function or a function object that compares type*. An example:

Code: Select all

struct type{
        int val;
};

struct comparator{
        bool operator()(const type * s1, const type * s2){
                return (s1 -> val < s2 -> val);
        }
};
You use it this way:

Code: Select all

priority_queue<type*, vector<type*>, comparator> q;