unary_function和binary_function详解

1. unary_function

1.1 unary_function介绍

        unary_funciton可以作为一个一元函数对象(又叫仿函数)的基类,它只定义了参数和返回值的类型本身并不重载()操作符,这个任务交给派生类去完成

1.2 unary_function源码

//TEMPLATE STRUCT unary_function
template<class _Arg, class _Result>
struct unary_function
{	//base class for unary functions
    typedef _Arg argument_type;
	typedef _Result result_type;
};
成员类型定义注释
argument_type第一个模板参数(Arg)()重载函数的参数类型
result_type第二个模板参数(Result)()重载函数的返回值类型

 1.3 unary_function例子

//unary_function example
#include <iostream>     // std::cout, std::cin
#include <functional>   // std::unary_function

//判断输入数据是否为Odd奇数?偶数是Even
struct IsOdd : public std::unary_function<int,bool> {
  bool operator() (int number) {return (number%2!=0);}
};

int main () 
{
  IsOdd IsOdd_object;
  IsOdd::argument_type input;
  IsOdd::result_type result;

  std::cout << "Please enter a number: ";
  std::cin >> input;

  result = IsOdd_object (input);

  std::cout << "Number " << input << " is " << (result?"odd":"even") << ".\n";

  return 0;
}

2. binary_function

2.1 binary_function介绍

        binary_function可以作为一个二元函数对象的基类,它只定义了参数和返回值的类型本身并不重载()操作符,这个任务交给派生类去完成

2.2 binary_function源码

//TEMPLATE STRUCT binary_function
template<class _Arg1,
	class _Arg2,
	class _Result>
struct binary_function
{	//base class for binary functions
	typedef _Arg1 first_argument_type;
	typedef _Arg2 second_argument_type;
	typedef _Result result_type;
};
成员类型定义注释
first_argument_type第一个模板参数(First_Arg)()重载函数的第一个参数类型
second_argument_type第二个模板参数(Second_Arg)()重载函数的第二个参数类型
result_type第三个模板参数(Result)()重载函数的返回值类型

 2.3 binary_function例子

//binary_function example
#include <iostream>     // std::cout, std::cin
#include <functional>   // std::binary_function

//比较两个数的大小
struct Compare : public std::binary_function<int,int,bool> {
  bool operator() (int a, int b) {return (a==b);}
};

int main () {
  Compare Compare_object;
  Compare::first_argument_type input1;
  Compare::second_argument_type input2;
  Compare::result_type result;

  std::cout << "Please enter first number: ";
  std::cin >> input1;
  std::cout << "Please enter second number: ";
  std::cin >> input2;

  result = Compare_object (input1,input2);

  std::cout << "Numbers " << input1 << " and " << input2;
  if (result)
  {
    std::cout << " are equal.\n";
  } 
  else
  {
    std::cout << " are not equal.\n";
  }
     
  return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小胖七少爷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值