Flexible use of C + + functions

Source: Internet
Author: User

C + + for the flexible use of functions, provides a number of language features and library support for function use. The first is support for language features, including function pointers and Lambda Expressions introduced in c++11 , and support for function use by standard libraries, including function adapters, and generic functions, which basically replace the use of function pointers.

First, the function pointer

int Love (const string &s) {    cout<< ' I love ' <<s<<endl;} int hate (const string &s) {    cout<< "I hate" <<S<<ENDL;} void Get_love (Decltype (Love) *fc,const string &s)  ///decltype The function type is not automatically converted to a function pointer, and the function argument cannot be a function type, so you need to add a pointer modifier {    FC (s); Int (*fis) (const string&); FIS = &love;  The address of love can be assigned to FIS FIS ("Hello, gnu!"); Auto LOVEP = Love;   LOVEP is a pointer to love Get_love (Lovep, "GCC"); Get_love (Hate, "Windows");

When the function pointer is overloaded, auto and decltype cannot be used, and the compiler cannot know what the program Ape wants for that function type, but the function pointer is also possible, but it must explicitly indicate the type of the function pointer, and there is no overloaded function pointer.

int Love (const string &s) {    cout<< "string" <<S<<ENDL;} int Love (const string &s,unsigned UI) {    cout<< "int" <<ui<< "\tstring" <<S<<ENDL;} Int (*lovepx) (const string&) = Love; Int (*lovepy) (const string&,unsigned) =love; LOVEPX ("Open Source"); Lovepy ("to C or not to C", 2);

Second, lambda expression

In addition to the function pointers, c++11 also introduces lambda expressions, each of which defines a lambda expression, or generates an inner class for it, and defines an object for that class.

Its simple to use:

  Vector<string> vs={"One", "one", "three", "four", "five", "six", "Seven"};  Sort (Vs.begin (), Vs.end (), [] (const string &x,const string &y) {///            The string is sorted by the size of the last letter             return * ( X.crbegin ()) < * (Y.crbegin ());       });  For_each (Vs.cbegin (), Vs.cend (), [] (const string& s) {///               output to standard output               cout<<s<<endl;           });  cout<<endl;
Lambda expressions are generally used to pass small operations inside a function, in which case we do not have to define a function and use the lambda expression directly, his restriction is that it cannot be shared between functions, and that too complex operations do not recommend using lambda expressions. When the return value is not too complex, and there is only one return statement, you can omit its return value declaration, which is automatically deduced by the compiler according to the return statement, and you can write as follows when you need to return a value

Vector<string> vs={"Follow", "My", "Heart", "!", "Run", "Say"};     Transform (Vs.cbegin (), Vs.cend (), Vs.begin (), [] (const string &s)->string               {                   if (s.size () > 5)                   {                       return S.substr (0,5);                   }                   else                   {                       return s;                   }               });    

In addition, lambda expressions can share local variables, and can be shared by value and shared by reference, such as:

Map<unsigned,string> mp={{0, "zero"},{1, "one"},{2, "one"}, {3, "three"},{4, "four"},{5, "five"};    int a=3; Share For_each by Value (Mp.cbegin (), Mp.cend (), [a] (const pair<unsigned,string> p) {if (p.f                  Irst > A) {cout<<p.first<< "\ T" <<p.second<<endl; } else {cout<<p.first<< "\ T" <<p.second+ "!"                  <<endl;    }              });    int sum=0;    Vector<int> vit = {1,2,3,4,5,6,7,8,9,0};             Share For_each by reference (Vit.cbegin (), Vit.cend (), [&sum] (int i) {sum + = i;    });                 A is shared by value, sum is shared by reference For_each (Vit.cbegin (), Vit.cend (), [a,&sum] (int i) {if (i > a)                 {sum + = i;    }             }); In addition to sum, all local variables are shared by value For_each (Vit.cbegin (), Vit.cend (), [=,&suM] (int i) {if (I < a) {sum + = i;        }             });                 Except for a, all local variables are shared by reference For_each (Vit.cbegin (), Vit.cend (), [&,a] (int i) {if (i! = a)                 {sum + = i; }             });
Third, about bind

Bind is introduced into the c++11, and the original complex parameters are bound to the same interface, which makes it simple

For example:

Remove Vector<unsigned> vs={0,1,2,3,4,5,6,7,8,9,10} from elements not less than 5; unsigned flag=5; Vs.erase (Remove_if (Vs.begin (), Vs.end (),              bind (less_equal<unsigned> (), std::p laceholders::_1,flag)), Vs.end ()); for (const auto &item:vs) {    cout<<item<<endl;}

WHERE std::p laceholders::_n refers to the argument that the nth parameter of the bound function is passed to the position of the pre-binding function that corresponds to the order in which the parameters appear in the bind adapter, as above, the first parameter of the resulting function (by std:: Placeholders::_1 indicator), which is the only parameterThe corresponding order that is passed to the less_equal<int>, that is, the first parameter (std::p lacesholders::_1 is the first of the BIND function Parameters section), and the second argument of Less_equal, The second in the bind function parameter portion of the flag when it is bound

With this feature, you can do more interesting things:

Sort vector<unsigned> vs={0,1,2,3,4,5,6,7,8,9,10} in descending order; Sort (Vs.begin (), Vs.end (),      bind (less_equal<unsigned> (), std::p laceholders::_2,std::p laceholders::_2)); for (const auto &item:vs) {    cout<<item<<endl;}

The BIND function can also be used to bind member functions

Class Boy{public:    void Love (const string &s) const    {        cout<< ' I love ' <<s<<endl;    }}; Boy by;string dear= "Beauty Girl"; auto FCX = Bind (&boy::love,by,std::p laceholders::_1); auto Fcy = Bind (&boy:: LOVE,STD::p laceholders::_1,dear); FCX (dear); fcy (by);
Note: Bind cannot be used to bind overloaded functions

Iv. about function

function is an adapter introduced in C++11 that provides a uniform interface to similar functions

For example:

Class boy{public:    int Love (const string &s) const    {        cout<< ' I love ' <<s<<endl;    }    int operator () (const string &s)    {    }};int Love (const string &s) {}boy By;auto LAMBDAF = [] (const string & ;) {return 0;}; Auto BINDF = bind (&boy::love,by,std::p laceholders::_1) vector<function<int (const string&) >> vf= {Lambdaf,bindf,love,by};vf[0] ("Apple"); Vf[1] ("Google"); Vf[2] ("Facebook"); Vf[3] ("IBM");

V. About MEM_FN and member functions in C + + as parameter passing

Function<bool (const string&) > FCX = &string::empty;  Call Function<bool by passing a reference (const string*) > Fcxx = &string::empty; Calls by passing a pointer to      ////either passing a reference or passing a pointer to call auto FCY = MEM_FN (&string::empty); auto Fcz = Bind (&STRING::EMPTY,STD:: placeholders::_1);   Vector<string> vs = {"American", "China", "Japan", "England", "Russia"};vs.erase (remove_if (Vs.begin (), Vs.end (), FCY), Vs.end ()), copy_if (Vs.begin (), Vs.end (), Vs.begin (), Fcz), find_if (Vs.begin (), Vs.end (), FCX);




Flexible use of C + + functions

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.