C + + 11-stl-function object (ON)

Source: Internet
Author: User

1. Definition

In STL, the function can be passed to the algorithm, or the function object can be passed to the algorithm.

So, what is a function object?

Let's take a look at its statement:

class x{public:  //  define function call operator  return operator Const ;  ...}

You can call this:
X fo;

...

Fo (arg1, arg2);

Let's look at a simple print example

PrintInt.h

#ifndef        Print_int_h_#define        print_int_h_<iostream>usingnamespace std; class Printint {public:    voidoperator() (int  Const     {        ';    }}; #endif

FuncObjectTest.h

#ifndef Stl_alg_func_object_test_h_#defineStl_alg_func_object_test_h_#include".. /.. /testbase.h"classFuncobjecttest: Publictestbase{ Public: Funcobjecttest (Const string&c,Const string&d): Testbase (c, D) {}voidrun ();Private:    voidprintfuncobject ();};#endif

FuncObjectTest.cpp

#include <vector>#include<algorithm>#include<iostream>#include"FuncObjectTest.h"#include".. /.. /core/printint.h"using namespacestd;voidfuncobjecttest::p rintfuncobject () {vector<int>Coll; //insert elements from 1 to 9     for(inti =1; I <=9; ++i) {coll.push_back (i); }    //Print all elementsFor_each (Coll.cbegin (), Coll.cend (),//RangePrintint ());//Operationcout <<Endl;}voidFuncobjecttest::run () {Printstart ("Printfuncobject ()");    Printfuncobject (); Printend ("Printfuncobject ()");}

Operation Result:

----------------Printfuncobject (): Run Start----------------
1 2 3 4 5 6 7 8 9
----------------Printfuncobject (): Run End----------------

C + + 11-stl-function object (ON)

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.