带有函数指针的映射

map with function pointers

本文关键字:映射 指针 函数      更新时间:2023-10-16

我得到了一个函数,它从给定的向量中返回一个最小值作为

    float minValue(vector<int> v){
      auto it = min_element(v.begin(), v.end());
      return *it;
    }

现在我有一张类似的地图

map<std::string, function*>
{
  {"min", /* here I need to use the above function call*/},
  //similarly for other requirements too
  {""}
 }

如何使用键来指向函数指针映射值?

您实际上是如何声明function的?你的地图定义应该看起来像

map<std::string, float (*)(vector<int> v)> fnMap {
    {"min", &minValue } ,
    {"", NULL } 
};

至于你的意见

typedef float(*function)(vector<int>);
map<std::string, function> fnMap {
    {"min", &minValue } ,
    {"", NULL } 
};

function*将产生一个指向函数指针的指针。