C++函数对象

//函数对象:
重载函数调用操作符的类, 其对象常称为函数对象(function object), 即它们是行为类
似函数的对象。 一个类对象, 表现出一个函数的特征, 就是通过“对象名+(参数列表)”的方式
使用一个类对象, 如果没有上下文, 完全可以把它看作一个函数对待。
这是通过重载类的 operator()来实现的。
“在标准库中, 函数对象被广泛地使用以获得弹性”, 标准库中的很多算法都可以使用函数
对象或者函数来作为自定的回调行为 

// 函数对象:可以像函数一样使用的对象
// 一元函数对象:参数只有一个
// 二元函数对象:参数有两个

 


 

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// 算法

void print(int num)
{
    cout << num << " ";
}

class Show
{
public:
    Show()
    {
        sum = 0;
    }
    void operator()(int num)
    {
        cout << num << " ";
        sum += num;
    }

public:
    int sum;
};

// 函数对象:可以像函数一样使用的对象
// 一元函数对象:参数只有一个
// 二元函数对象:参数有两个
void func()
{
    vector<int>  v;
    for (int i = 0; i < 10; i++)
        v.push_back(i);

    /*
     * for (it = v.begin(); it != v.end(); it++)
     * {
     *     XXX(*it);
     * }
    */
    for_each(v.begin(), v.end(), print);
    cout << endl;

    Show s;
    s = for_each(v.begin(), v.end(), s);
    cout << endl;

    cout << s.sum << endl;

}
int main()
{
    func();
    return 0;
}

运行结果是

0 1 2 3 4 5 6 7 8 9

0 1 2 3 4 5 6 7 8 9

45

 

 

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void print(int num)
{
    cout << num << " ";
}

int add(int a, int b)
{
    return a+b;
}

class Mul
{
public:
    int operator()(int a, int b)
    {
        return a*b;
    }

};

// 二元函数对象
void func()
{
    vector<int> v1;
    v1.push_back(1);
    v1.push_back(2);
    v1.push_back(3);

    vector<int> v2;
    v2.push_back(4);
    v2.push_back(5);
    v2.push_back(6);

    vector<int> v3(3);

    /*
     * for (it1 = v1.begin(), it2 = v2.begin(), it3 = v3.begin(); it1 != v1.end(); it1++, it2++, it3++)
     * {
     *     *it3 = XXX(*it1, *it2);
     * }
    */
    transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), add);
    for_each(v3.begin(), v3.end(), print);
    cout << endl;

    transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), Mul());
    for_each(v3.begin(), v3.end(), print);
    cout << endl;


}

int main()
{
    func();
    return 0;
}

运行结果

5 7 9

4 10 18

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值