7 仿函数

7.1 仿函数概念

使用方法:

greater<int> ig;
cout << ig(4,6);  //常规用法
cout << greater<int>()(6,4); //使用临时对象。

7.2 可配接的关键

为了拥有可配接能力,每一个仿函数必须定义自己的相应型别。为了方便,定义了两个class,分别代表一元仿函数和二元仿函数(STL不支持三元仿函数)。任何仿函数,只有继承其中一个class,就可以获得相应型别,也就自动拥有了配接能力。

1、unary_function——用于一元函数

template <class Arg, class Result>
struct unary_function {
	typefef Arg argument_type;
	typedef Result result_type;
}
2、binary_function——用于二元函数

template <class Arg1, class Arg2, class Result>
struct binary_function{
	typedef Arg1 first_argument_type;
	typedef Arg2 secong_argument_type;
	typedef Result result_type;
}


7.3 算数类仿函数

plus<T> minus<T> multiplies<T> divides<T> modules<T> negate<T>

template <class T>
struct plus : public binary_function<T, T, T> {
	T operator()(const T& x, const T& y) const{result x + y;}
};

7.4 关系运算符

equal_to<T> not_equal_to<T> greater<T> greater_equal<T> less<T> less_equal<T>

template <class T>
struct equal_to : public binary_function<T, T, bool> {
	T operator()(const T& x, const T& y) const{result x == y;}
};

7.5 逻辑运算符

logical_and<T> logical_or<T> logical_not<T>


7.6 证同(identity)、选择(select)、投射(project)

这些仿函数只是将参数原封不动的传回,这只是为了间接性,间接性是抽象化的重要工具。

template <class T>
struct idendity : public unary_function<T, T>{
	const T& operator()(const T& x) const { return x; }
};

template <class Pair>
struct select1st : public unary_function<Pair, typename Pair::first_type> {
	const typename Pair::first_type& operater()(const Pair& x) const { return x.first; }
};

template <class Pair>
struct select2nd : public unary_function<Pair, typename Pair::second_type> {
	const typename Pair::second_type& operater()(const Pair& x) const { return x.second; }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值