【问题标题】:How to asaign lambda funcion in unordered_map with cpp?如何使用 cpp 在 unordered_map 中分配 lambda 函数?
【发布时间】:2018-05-04 18:01:23
【问题描述】:

目前正在尝试学习 c++,我正在尝试制作一个“寻找 wumpus”应用程序来帮助我学习。我在将 lambda 函数分配给 C++ 中的 unordered_map 时遇到问题。我的 IDE 给了我错误 “参数类型不匹配:不兼容的指针类型'node *const'和'node ()(node *)'”

#include <iostream>
#include <string>
#include <unordered_map>
class node{
public:
    int title;
    node *adj[8];
    std::string desc;
}
...
bool shoot(node *player){
std::unordered_map<std::string, node*> adjLambda; //lambda to return *left, *up, etc

    for (int i; i < 8; i++){
        if (player->adj[i]->title != player->title){ //empty adjacencies points towards self
            adjLambda.insert(std::pair <std::string, node*> (std::to_string(player->adj[i]->title), [](node *n) { return n->adj[i];}));
        }
    }
}

【问题讨论】:

  • 您的地图将std::string 作为键,node* 作为值。 lambda 不是这两种类型,那么您为什么希望能够将一个插入到该映射中?
  • 我更习惯于python和java等高级语言,对c++还是很陌生。你介意我问如何定义一个 lambda 吗?
  • “定义一个 lambda”是什么意思?无论您编写什么,您的地图都不会包含任何其他类型,而不是它声明的类型,并且 lambda 永远不会是这些类型中的任何一种。如果您想在映射中保存 lambda,请让映射保存 std::function 对象 - 可以将 lambda 存储在这些对象中(假设它采用正确的参数并返回正确的类型以匹配 std::function 的签名)。

标签: c++ dictionary lambda


【解决方案1】:

您可以包含&lt;functional&gt;,然后将值存储为std::function

void shoot(node *player){
    std::unordered_map<std::string, std::function<node*(node*)>> adjLambda; //lambda to return *left, *up, etc

    for(int i{}; i < 8; i++){
        if(player->adj[i]->title != player->title){ //empty adjacencies points towards self
            adjLambda.insert(           // insert into the unordered map
                std::pair<              // pair to be inserted
                    std::string,        // key is a string
                    std::function<      // map entry is a function
                        node*(node*)    // function takes a node pointer and returns a node pointer
                    >
                >(
                    std::to_string(player->adj[i]->title),  // create a string to use as the key
                    [i](node *n) { return n->adj[i]; }      // lambda that takes a node pointer and returns another
                )
            );
        }
    }
}

【讨论】:

  • 请问这是在做什么? adjLambda.insert(std::pair <:string std::function>>(STD::TO_STRING(PLAYER->ADJ[I]->TITLE), [I](node *n) { return n->adj[i]; }));
  • @12Bits 发生了很多事情,所以我解压了一下。
  • @wally std::make_pair 会缩短很多
  • @MihaylA.A 是的,是的。 emplace 也是一个不错的选择。
  • @wally 函数会产生更好的性能,还是我现在应该关心自己的性能?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-08
  • 1970-01-01
相关资源
最近更新 更多