C++中的仿函数

更多文章欢迎访问 程序员小非 博客

定义

functor的英文解释为something that performs a function,即其行为类似函数的东西。C++中的仿函数是通过在类中重载()运算符实现,使你可以像使用函数一样来创建类的对象。

C中是怎么实现这个功能的

使用指针函数和回调函数,比如qsort的比较函数

#include <stdio.h>
#include <stdlib.h>
int sort_function( const void *a, const void *b) {
      
	return *(int*)a-*(int*)b;
}
int main() {
   
   int list[5] = {
    54, 21, 11, 67, 22 };
   qsort((void *)list, 5, sizeof(list[0]), sort_function);    //起始地址,个数,元素大小,回调函数 
   int  x;
   for (x = 0; x < 5; x++)
       printf("%i\n", list[x]);
   return 0;
}
C++ 中的仿函数
  • 一个例子(增加任意常数)
// this is a functor
struct add_x {
   
  add_x(int x) : x(x) {
   }
  int operator()(int y) {
    return x + y; }
private:
  int x;
};

// usage:
add_x add42(42); // create an instance of the functor class
int i = add42(8); // and "call" it
assert(i == 50); // and it added 42 to its argument
std
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值