将函数作为参数传递 C++

问题描述

我知道这个问题可能已经重复了很多次,但我不明白他们的答案。所以我们开始:

我有一个 double* 类型的数组,它作为一个名为 arr 的指针传递,数组的大小作为 int arrsize 参数传递。现在,这是我感到困惑的地方,我想使用参数 typeOfOper 对数组中的元素执行函数指针 val 指定的操作。

void fnoper(double *arr,int arrsize,void (*typeOfOper)(double*,int,const double),const double val);

我还有其他四个函数可以执行不同类型的操作(addsubtractdividemultiply)。同样,根据传递的操作类型 (typeOfOper),该函数将执行其他四个函数之一。

如果有人能指导我并让我知道我能做什么,我将不胜感激。感谢您抽出宝贵时间。

解决方法

这是您的示例的用法示例。我可以使用指向本地函数 fnOperoperSum 的指针调用函数 operSubstract,如下所示:

    // call with sum
    fnOper(arrList,arrListSize,operSum,15.3);
    // call with substract
    fnOper(arrList,operSubstract,15.3);

这是完整的编译示例:

#include <iostream>

void operSubstract(double* a,int sizeOfa,const double z) {
    for (int i=0; i<sizeOfa; i++)
    {
        std::cout << std::fixed << *(a+i) << " MINUS ";
    }
    std::cout << z;
    std::cout << std::endl;
}

void operSum(double* a,const double z) {

    for (int i=0; i<sizeOfa; i++)
    {
        std::cout << std::fixed << *(a+i) << " PLUS ";
    }
    std::cout << z;
    std::cout << std::endl;
}

void fnOper(double *arr,int arrsize,void (*typeOfOper)(double* x,int y,const double z),const double val)
{
    (*typeOfOper)(arr,arrsize,val);
}

int main()
{
    // to display only 2 floating points to be good looking
    std::cout.precision(2);

    // preparation of actual arguments to use the functions with
    double arrList[] = {25.3,15.2,3.6};


    int arrListSize = sizeof(arrList)/sizeof(double);
    // call with sum
    fnOper(arrList,15.3);

    // call with substract
    fnOper(arrList,15.3);

}

结果如下:

25.30 PLUS 15.20 PLUS 3.60 PLUS 15.30
25.30 MINUS 15.20 MINUS 3.60 MINUS 15.30
,

我们经常可以使用 std::function<void(double*,size_t)> 来保存函数和类函数对象。最大的优势是您不再需要单独的 const double val

void fnOper(double *arr,size_t len,std::function<void(double*,size_t)> fun)
{
  fun(arr,len); // Simple
}

template <size_t LEN>
void fnOper(double (&arr)[LEN],LEN); // Can also work on arrays
}
void add5 (double* ptr,size_t len) { 
   for (size_t i = 0; i != len; ++i) ptr[i] += 5.0;
}
double d[] = { 2.0,3.0,4.0 }
fnOper(d,add5)

但我们通常不会编写这样的代码 - 当我们想要遍历数组、向量或列表时,已经有 std::transform 了。