【问题标题】:Storing functions in data structure to later find and call them将函数存储在数据结构中以供以后查找和调用它们
【发布时间】:2017-11-30 14:02:54
【问题描述】:

我正在考虑创建一个程序来将函数存储在无序映射中。是否可以通过他们的钥匙找到他们并打电话给他们?我也想在其他模块中使用它作为头文件。它会寻址相同的内存地址位置还是每次都生成新的内存?

【问题讨论】:

    标签: c++ data-structures heap-memory unordered-map


    【解决方案1】:

    你是说

    std::unordered_map<some_key_type, std::function<Output(Input)>> functions;
    // ...
    functions[some_value](some_input);
    

    ?

    如果你这样做,请参阅相关文档:

    【讨论】:

    • 就像那个YSC
    • @ShubhamJangam 请注意,这要求所有函数具有相同的参数类型和相同的返回类型。如果不是这样,它仍然可能更痛苦
    • @tobi303 这将是一个很好的第二个答案。 (我的第 100 票确实获得了体育精神徽章:)
    • 但是你没有回答我的第二个问题。 .....如果我将该文件用作其他文件中的标题,是否会在内存中创建多个副本? @YSC
    • @ShubhamJangam 每个问题一个问题,这是对 SO 的预期。您应该使用minimal reproducible example 提出另一个问题,因为答案取决于它。
    【解决方案2】:
    #include <functional>
    using namespace std;
    
    int add(int a, int b)
    {
           return a+b;
    }
    int main()
    {
           unordered_map<int , function<int(int,int) >> umap ;
           //umap[1](5,10);
    
    }
    **
     output :
      std : bad function call
    
    enter code here
    **
    I want to map that function attibute in value section to int add function 
    I am unable to map it or how I can write the 'values' function body
    

    【讨论】:

      【解决方案3】:

      您还没有为 umap 的键 1 分配任何功能。

      umap.insert(make_pair(1, add));
      

      这样就可以了。

      【讨论】:

      • 没有put之类的功能
      • 不要给函数参数..只要做(1,添加)
      • 或 umap.insert({1, add});
      • 如何调用这些函数并存储ans
      • 谢谢!完成!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 2015-02-12
      • 2019-01-19
      • 1970-01-01
      相关资源
      最近更新 更多