STL functor

In "Analysis of STL Source Code", a separate explanation is used to describe functors. Functors are mainly used in the implementation of algorithms to implement various functions of an algorithm, such as the sort function, which enables users to customize sorting through the functor mechanism. rule.

For the explanation of functors, please refer to the book "Analysis of STL Source Code", blog: https://blog.csdn.net/yzhang6_10/article/details/51297424 Also make some summary notes on the content of the book, paste a piece of code below Help understand:

#include<iostream>

#include<vector>

#include<algorithm>

using namespacestd;

bool comp2( const int &a, const int &b) //When the function pointer is passed in as the parameter of sort, the function can only be a global function or a static member function, and the non-static member function in the class will report an error  

{

    return a>b;

}


struct compare {  //struct compare:public binary_function<int,int,bool>{ //STL needs to inherit like this, so that users can use the parameter types of functors, no analysis is done here, you can refer to "STL Source Code Analysis"

    bool operator()(const int& x,const int& y)const{

        return x<y;

    }

};

/* A standard functor in STL

 template<class T>

 struct greater:public binary_function<T,T,bool>{

 bool operator()(const T& x,const T& y) const{

 return x>y;

 }

 */

intmain ()

{

    vector<int>vec;

    vec.push_back(33);

    vec.push_back(237);

    vec.push_back(93);

    vec.push_back(186);

    vec.push_back(32);

    compare comp1;

    sort (vec.begin (),vec.end ( ), comp1 ); //pass in a functor object 

    /*

     As for how the incoming comp1 object will be used, you can imagine that the return value of comp1() will be used inside the sort sorting function, for example (the STL sort source code is not necessarily the case):

     int max=comp1(x1,x2)?x1:x2; Then apply max to the sorting, so as to achieve sorting according to the rules we give

     */

    for(int i=0;i<vec.size();i++)

    {

        cout<<vec[i]<<" ";

    }

    cout<<endl;

    sort (vec. begin (), vec. end (), comp2 ); // pass in the function pointer

    for(int i=0;i<vec.size();i++)

    {

        cout<<vec[i]<<" ";

    }

    cout<<endl;

    sort (vec.begin ( ),vec.end ( ), compare ()); //pass in a temporary functor object 

    for(int i=0;i<vec.size();i++)

    {

        cout<<vec[i]<<" ";

    }

    cout<<endl;

    //system("pause");

    return0;

}

If you have any questions or are unclear, you can leave a message to communicate~

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325856798&siteId=291194637