当前位置:网站首页>Function object (functor)

Function object (functor)

2022-06-09 22:02:00 Gy648

Function object ( functor )

Function objects can be called like ordinary functions when used , There can be parameters , You can have a return value
Function objects can go beyond the concept of ordinary functions , Function objects can have their own states
Function objects can be passed as arguments

class myadd
{
    
public:
   int operator()(int v1,int v2) // Overloading function callers 
   {
    
       return v1+v2;
   }
};
  • Function objects are used , You can call... Like a normal function
void test01()
{
    
    myadd myadd;
    cout<<myadd(10,10)<<endl;
}
  • Function objects can have their own state
class myprint
{
    
public:
    myprint()
    {
    
        this->count=0;
    }
    void operator()(string test)
    {
    
        cout << test << endl;
        this->count++;
    }
    int count = 0;
};
void test01()
{
    
    myprint myprint;
    myprint("hello");
    myprint("hello");
    myprint("hello");
    myprint("hello");
    myprint("hello");
    cout<<" count = "<<myprint.count<<endl;

}

Different from ordinary functions , A mock function is not called like an ordinary function , Destroyed as the call ends , You can have your own internal records

  • Function objects can be passed as arguments
class myprint
{
    
public:
    myprint()
    {
    
        this->count = 0;
    }
    void operator()(string test)
    {
    
        cout << test << endl;
        this->count++;
    }
    int count = 0;
};
void doprint(myprint &mp, string test)
{
    
    mp(test);
}
void test01()
{
    
    myprint myp;
    doprint(myp, "aaaaaa");
}

The predicate

return bool A functor of type is called a predicate
If opertor() Take a parameter , Is a unary predicate
Two parameters , Is a binary predicate

Unary predicate

class overfive
{
    
public:
    bool operator()(int val)
    {
    
        return val > 5;
    }
};
void test01()
{
    
    vector<int> v;
    for (int i = 0; i < 10; i++)
    {
    
        v.push_back(i + 1);
    }
    vector<int>::iterator it = find_if(v.begin(), v.end(), overfive());
    find_if(v.begin(), v.end(), overfive()); // Pass in an anonymous function object 
    // The return value is the iterator position , Find one greater than 5 The number of 
}

two-place predicate

class mycomper
{
    
public:
    bool operator()(int v1, int v2)
    {
    
        return v1 > v2;
    }
};
void test01()
{
    
    vector<int> v;
    v.push_back(10);
    v.push_back(45);
    v.push_back(21);
    v.push_back(35);
    v.push_back(12);
    sort(v.begin(), v.end(),mycomper());
}
原网站

版权声明
本文为[Gy648]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206092118511460.html