浅析C++仿函数,如何改写为长尾词?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1897个文字,预计阅读时间需要8分钟。
1. 为什么需要仿函数? 我们先从一个非常简单的实际问题入手。假设我们有一个数组,其中包含任意数量的数字,我们希望计算出这个数组中大于10的数字的数量。你的代码应该非常简洁易懂。
1.为什么要有仿函数
我们先从一个非常简单的问题入手。假设我们现在有一个数组,数组中存有任意数量的数字,我们希望能够计数出这个数组中大于10的数字的数量,你的代码很可能是这样的:
#include <iostream> using namespace std; int RecallFunc(int *start, int *end, bool (*pf)(int)) { int count=0; for(int *i=start;i!=end+1;i++) { count = pf(*i) ? count+1 : count; } return count; } bool IsGreaterThanTen(int num) { return num>10 ? true : false; } int main() { int a[5] = {10,100,11,5,19}; int result = RecallFunc(a,a+4,IsGreaterThanTen); cout<<result<<endl; return 0; }
RecallFunc()函数的第三个参数是一个函数指针,用于外部调用,而IsGreaterThanTen()函数通常也是外部已经定义好的,它只接受一个参数的函数。
本文共计1897个文字,预计阅读时间需要8分钟。
1. 为什么需要仿函数? 我们先从一个非常简单的实际问题入手。假设我们有一个数组,其中包含任意数量的数字,我们希望计算出这个数组中大于10的数字的数量。你的代码应该非常简洁易懂。
1.为什么要有仿函数
我们先从一个非常简单的问题入手。假设我们现在有一个数组,数组中存有任意数量的数字,我们希望能够计数出这个数组中大于10的数字的数量,你的代码很可能是这样的:
#include <iostream> using namespace std; int RecallFunc(int *start, int *end, bool (*pf)(int)) { int count=0; for(int *i=start;i!=end+1;i++) { count = pf(*i) ? count+1 : count; } return count; } bool IsGreaterThanTen(int num) { return num>10 ? true : false; } int main() { int a[5] = {10,100,11,5,19}; int result = RecallFunc(a,a+4,IsGreaterThanTen); cout<<result<<endl; return 0; }
RecallFunc()函数的第三个参数是一个函数指针,用于外部调用,而IsGreaterThanTen()函数通常也是外部已经定义好的,它只接受一个参数的函数。

