08~函数对象/函数符

1. 函数符定义

函数对象,也叫做函数符,定义:
函数符是可以和()结合起来完成函数调用的符号,有三种
函数名,函数指针,重载了operator()()函数的对象

#include <iostream>
#include <list>
#include <algorithm>

using namespace std;
/*function name*/
/*function ptr*/
/*operator()(...)*/


void out_int(int const& that)
{
	cout << that << ' ';
}

bool tooBig(int const that)
{
	return that > 50;
}

template <typename T>
class tooBig2
{
private:
T m_cut;
public:
	tooBig2(T const& val):m_cut(val){}

	bool operator()(T const& that)
	{
		return that > m_cut;
	}
	
};



void ((*out_int_ptr)(int const&)) = out_int;
 
int main()
{
int vals[10] = {10,20,30,40,50,60,70,80,90,100};
list<int> list1(vals,vals + 10);

/*out_int(*iterator)*/
for_each(list1.begin(),list1.end(),out_int);
cout << endl; /*10~100*/

/*out_int_ptr(*iterator)*/
for_each(list1.begin(),list1.end(),out_int_ptr);
cout << endl; /*10~100*/

/*tooBig(*iterator)*/
list1.remove_if(tooBig);
for_each(list1.begin(),list1.end(),out_int_ptr);
cout << endl; /*10~50*/

tooBig2<int> big40(40);
/*big40(*iterator)*/
list1.remove_if(big40);
for_each(list1.begin(),list1.end(),out_int_ptr);
cout << endl; /*10~40*/


return 0;
}

2. 预定义的函数符

运算符函数符
+plus
-minus
*multiplies
/divides
%modulus
-negate
==equal_to
!=not_equal_to
>greater
<less
>=greater_equal
<=less_equal
&&logical_and
||logical_or
!logical_not

示例用法

#include <fuctional>
plus<double> add;
double y = add(2.2,2.3);

3. 自适应函数符

2. 一节中例举的函数符都是自适应函数符:自适应函数定义了参数类型与返回类型

//一元函数结构
template <class Arg, class Result>
struct unary_function 
{
    typedef Arg argument_type; //参数类型,可以理解为x对应的类型
    typedef Result result_type;//返回值类型,可以理解为 z 对应的类型
};
//二元函数结构
template <class Arg1, class Arg2, class Result>
struct binary_function
 {
    typedef Arg1 first_argument_type; //第一个参数类型,可以理解为x对应的类型
    typedef Arg2 second_argument_type;//第二个参数类型,可以理解为y对应的类型
    typedef Result result_type; //返回值类型,可以理解为 z 对应的类型
};

自适应函数符

//取负,接受一个参数
template <class T>
struct negate : public unary_function<T, T> {
    T operator()(const T& x) const { return -x; }
};

//小于,接受两个参数
template <class T>
struct less : public binary_function<T, T, bool> {
    bool operator()(const T& x, const T& y) const { return x < y; }
};

4. 自适应适配器

自适应函数符可以结合适配器生成新的函数符
读者可以参看有关bind1st模板类的stl实现
https://www.cnblogs.com/chuyongliu/p/5308616.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值