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.
STL priority queue
Moderator: Board moderators
-
- Experienced poster
- Posts: 154
- Joined: Sat Apr 17, 2004 9:34 am
- Location: EEE, BUET
STL priority queue
You should never take more than you give in the circle of life.
-
- Guru
- Posts: 584
- Joined: Thu Jun 19, 2003 3:48 am
- Location: Sanok, Poland
- Contact:
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_.
[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_.
-
- Experienced poster
- Posts: 154
- Joined: Sat Apr 17, 2004 9:34 am
- Location: EEE, BUET
-
- Guru
- Posts: 584
- Joined: Thu Jun 19, 2003 3:48 am
- Location: Sanok, Poland
- Contact:
It's quite straightforward. You must provide a function or a function object that compares type*. An example:
You use it this way:
Code: Select all
struct type{
int val;
};
struct comparator{
bool operator()(const type * s1, const type * s2){
return (s1 -> val < s2 -> val);
}
};
Code: Select all
priority_queue<type*, vector<type*>, comparator> q;