如何使用cpp在unordered_map中设置lambda函数?

时间:2018-05-04 18:01:24

标签: c++ dictionary lambda

目前正在尝试学习c ++,而我正试图制作一个"捕捉wumpus"应用程序,以帮助我学习。我在将一个lambda函数分配给C ++中的unordered_map时遇到了麻烦。我的IDE给了我错误 "参数类型不匹配:不兼容的指针类型'节点* const'和'节点)(节点*)'"

#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];}));
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以添加<functional>,然后将值存储为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
                )
            );
        }
    }
}