STL is convienient to use and has much benifits over robustness and performance. For algorithms like sorting and priority queue, we need comparision function to decide order among elements . It is easy to do so when the element is our own class. We need only write the less operator. like this
class foo
{
.....
` bool operator < (const foo& _right) { return value <>
Then when you sort a vector e.g. vectorvf, it will be sorted according to value.
When we use standard containers like or types, we don't have chance to override the less function.
then. we can use functional object. (an object act as function) here are examples.
1. define a function object for the object to sort.
class fobj_comp{
public:
bool operator () (const foo& _p1, const foo& _p2) const
{
return _p1.another_value <>
and supply it to sort routine sort(vf.begin(), vf.end(), fobj_comp());
so that we can sort the vector on "another_value" without need to modify the inside "<" operator. 2. Use functional object for dereferencing " pair*"
class fobj_comp{
public:
bool operator () (const pair* _p1, const pair * _p2) const
{
return _p1->first <>first;
}
}
and then define the prioirty queue as
priority_queue <>* , vector* > , fobj_comp> my_pq;
so that priority function is defined as fobj_comp;
The EFF_STL book suggests base such fobj_comp on
binary_function<>*, pair* >
changing it to
class fobj_comp :
public binary_function<>*, pair* >
{
//same as previous body
}
They have the same effect for the code segment.
One point is in operation def. We can not write
bool operator () (const foo*& _p1, const foo*& _p2) const
{
.....
}
The compiler can not read "foo*&" use "foo*" or typedef foo* pfoo, and const pfool& works
[Thanks]
Jency for EFF_STL, Shu'an for finding the last point. , Mr. google
Ref. Effect_STL book. (ask Mr. google for details)
没有评论:
发表评论