函数对象(仿函数)、谓词(20221126)

一、函数对象

1、函数对象概念

重载函数调用操作符的类,其对象称为函数对象。

函数对象使用重载的()时,其行为类似函数调用,也叫仿函数。

函数对象(仿函数)本质上是一个类 不是一个函数。

2、函数对象的使用

特点:

使用时可以像普通函数调用一样,可以有参数和返回值。

函数对象超出了普通函数的概念,可以有自己的状态。

函数对象可以作为参数传递。

class MyAdd {

public :

    int operator()(int v1, int v2)

    {

        return v1 + v2;

    }

};



class MyPrint {

public:

    MyPrint()

    {

        this->count = 0;

    }



    void operator()(string test)

    {

        cout << test << endl;

        count++;

    }

    int count; // 内部自己的状态 记录调用次数



};



void doPrint(MyPrint&mp, string test)

{

    mp(test);

}



void test01()

{

    MyAdd myAdd;

    //使用时可以像普通函数调用一样,可以有参数和返回值

    cout << myAdd(10, 10) << endl;//20

    //函数对象超出了普通函数的概念,可以有自己的状态。如下面输出调用次数

    MyPrint myPrint;

    myPrint("HHHH");

    myPrint("ABC");

    myPrint("BCV");

    myPrint("LLL");

    cout << "调用次数" << myPrint.count << endl;//4

    //函数对象可以作为参数传递。

    MyPrint myPrint1;

    doPrint(myPrint1, "hello c++");

}

二、谓词

1、谓词概念

返回bool类型的仿函数称为谓词;

如果operator()接受一个参数,那么叫做一元谓词,接收两个参数,叫做二元谓词。

class GreaterFive {

public:

    bool operator()(int val)//一元谓词 只有一个参数

    {

        return val > 5;

    }

};



class MyCompare {

public:

    bool operator()(int val1, int val2) //二元谓词 有两个参数

    {

        return val1 > val2;

    }

};





void test02()

{

    //一元谓词

    vector<int>V;

    for (int i = 0; i < 10; i++)

    {

        V.push_back(i);//插入10个元素

    }

    //寻找其中大于5的数

    vector<int>::iterator pos = find_if(V.begin(),V.end(),GreaterFive());//GreaterFive()为匿名对象  find_if返回的是迭代器

    if (pos == V.end())

    {

        cout << "没有找到大于5的数" << endl;

    }

    else

    {

        cout << "找到大于5的数" << *pos << endl;

    }



    //二元谓词

    //对容器进行排序 改变默认排序规则,从大到小

    vector<int>V1;

    for (int i = 0; i < 10; i++)

    {

        V1.push_back(i);//插入10个元素

    }

    sort(V1.begin(), V1.end(), MyCompare());//MyCompare()匿名对象



    for (vector<int>::iterator it = V1.begin(); it != V1.end(); it++)

    {

        cout << *it << " ";

    }

} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值