Как включить лямбда-функцию в unordered_map с помощью cpp? - PullRequest
0 голосов
/ 04 мая 2018

В настоящее время я пытаюсь выучить c ++, и я пытаюсь создать приложение для "охоты на козла", которое поможет мне учиться. У меня возникают проблемы с назначением лямбда-функции unordered_map в C ++. Моя 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];}));
        }
    }
}

1 Ответ

0 голосов
/ 04 мая 2018

Вы можете включить <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
                )
            );
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...