C ++ is really good. In the previous chapter, we talked about replacing the function pointer with a function object. Today, I flipped through and saw the STL function object, the truth is similar to the previous chapter. The only difference is that if STL function objects are used, remember that these function objects inherit the standard function objects: STD: binary_function (binary function) STD: unary_function (mona1 function ). Or overload the operator () operator. This STL function can be an inline function and can use the algorithm of the standard library. It is necessary to learn about it.
The following example is based on the content in the book. popless is a relatively large function. isten is simpler, that is, to judge whether the class ID is 10. Let's take a look.
# Include <iostream>
# Include <algorithm>
# Include <stdlib. h>
# Include <time. h>
Using namespace STD;
Class state
{
// A class which has ID as its member
Public:
State (): m_id (0 ){}
Void set_id (int id) {m_id = ID ;}
Int ID () const {return m_id ;}
PRIVATE:
Int m_id;
};
Struct popless: public STD: binary_function <state, state, bool>
{
Bool operator () (const State & A, const State & B) const
{Return a. ID () <B. ID ();}
};
Struct isten: public STD: unary_function <state, bool>
{
Bool operator () (const State & A) const
{Return a. ID () = 10 ;}
};
Int main (INT argc, char * argv [])
{
State St [10];
Srand (INT) time (0 ));
Cout <"create st..." <Endl;
For (int ix = 0; ix <10; ix ++)
{
Int id = 1 + (INT) (10.0 * rand ()/(rand_max + 1.0 ));
St [ix]. set_id (ID );
Cout <st [ix]. ID () <Endl;
}
Cout <"create over..." <Endl;
Sort (St, ST + 10, popless ());
Cout <"after sort st..." <Endl;
For (int ix = 0; ix <10; ix ++)
{
Cout <st [ix]. ID () <Endl;
}
Cout <"display over..." <Endl;
State * tenstate = find_if (St, ST + 10, isten ());
If (tenstate! = ST + 10)
{
Cout <"find 10" <Endl;
}
Else
{
Cout <"can't find 10" <Endl;
}
System ("pause ");
Return 0;
}