STL函数对象之自定义函数对象

如何定义自己的函数对象,它使用于任何的绑定器
要定义自己的绑定器要满足一定的条件:必须提供参数和返回值的类型。
STL 为我们提供了两个结构体:
template <class Arg, class Result>
struct unary_function {
typedef Arg argument_type;
typedef Result result_type;
};
template <class Argl, class Arg2, class Result>
struct binary_function {
typedef Argl first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};


一个例子:
template <class T1, class T2>
struct fopow : public std::binary_function<T1, T2, T1>
{
T1 operator() (T1 base, T2 exp) const {
return std::pow(base,exp);
}
};

for (int i=1; i<=9; ++i) {
coll.push_back(i);
}
transform (coll.begin(), coll.end(), //source
ostream_iterator<int>(cout," "), //destination
bind1st(fopow<float ,int>() ,3)); //operation
cout << endl;
output:
3 9 27 81 243 729 2187 6561 19683.

在我们自定以函数对象时也不必非要继承那两个结构体,在自己类指定相关类型也可以。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值