C++第11课 迭代器与仿函数 (二)

1.仿函数

/*
    仿函数:让类的对象模仿函数调用的行为(函数名())
    //对象()  关键点在于重载()
    仿函数一般来说用来做比较准则
    充当for_each的参数
    No.1 自己写仿函数
*/
class Sum
{
public:
    int operator()(const int a, const int b) const
    {
        return a + b;
    }
    //自己写仿函数
};

int main()
{
    //重载()的调用方式
    Sum object;
    cout << Sum()(1, 2) << endl;                //1.采用无名对象调用重载函数
    //operator()函数名
    cout << object.operator()(1, 2) << endl;    //2.调用成员函数的方式
    cout << object(1, 2) << endl;                //3.重载的调用方式
    //用的比较多的仿函数 less<_Ty> greator<_Ty>
    map<int, string> initMap;
    map<int, string, less<int>> lessMap;
    map<int, string, greater<int>> greatorMap;
    //标准库中的仿函数
    //1.算术类
    cout << plus<int>()(1, 2) << endl;
    cout << minus<int>()(1, 2) << endl;
    //2.关系:
    cout << greater_equal<int>()(1, 2) << endl;   //>=
    //less_equal   <=
    //not_equal_to !=
    //equal_to :  ==
    //3.逻辑运算符
    cout << logical_and<int>()(1, 2) << endl;   //1&&2
    return 0;
}
原文地址:https://www.cnblogs.com/creature-lurk/p/15252836.html