如何在 unordered_map 中使用 cpp 来识别 lambda 函数?

How to asaign lambda funcion in unordered_map with cpp?

本文关键字:cpp 识别 lambda 函数 unordered map      更新时间:2023-10-16

目前正在尝试学习 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];}));
}
}
}

您可以包含<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
)
);
}
}
}