C++——仿函数

它是个类,不是个函数。

模仿函数的类:能像普通函数一样传入给定数量的参数,还能存储或者处理更多我们需要的有用信息

https://www.cnblogs.com/decade-dnbc66/p/5347088.html

class StringAppend{
    public:
        explicit StringAppend(const string& str) : ss(str){}

        void operator() (const string& str) const{
             cout<<str<<' '<<ss<<endl;
        }
    
    private:
        const string ss;  
};

StringAppend myFunc("is world");
myFunc("hello");
>>>hellois world
class ShorterThan {
    public:
        explicit ShorterThan(int maxLength) : length(maxLength) {}
        bool operator() (const string& str) const {
            return str.length() < length;
        }
    private:
        const int length;
};
count_if(myVector.begin(), myVector.end(), ShorterThan(length));//直接调用即可

猜你喜欢

转载自www.cnblogs.com/yrm1160029237/p/10222097.html
今日推荐