STL function object

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.