gpt4 book ai didi

c++ - 我正在尝试制作字符串函数的 HashMap

转载 作者:行者123 更新时间:2023-11-28 00:10:18 25 4
gpt4 key购买 nike

我正在尝试制作一个将字符串存储为标识符的映射和一个返回字符串的函数我已经尝试过 typedef 但我一直遇到问题,因为我无法将我的 typedef 字符串(命令)()转换为常规字符串我也尝试过 map 命令,但它给了我一个表达式预期错误,但如果我用 int 替换字符串它确实有效。有人知道这样做的方法吗?这是我的代码的样子

        #include "iostream"
#include <map>
#include <functional>


using namespace std;

class GameController {

public:
void inputReader();

private:


bool gameOver = false;
map<string,string(*)()> commands;//Does not work

//commands
string commandReader(string* inputCommand);
void initCommands();

//both
char* end();
string run();

//while attacking
string attack();
string usePotion();
string useItem();

//while in room
string engage();
string searchRoom();
string rest();
string checkBag();
string checkMap();
string checkStats();
//string save();



};



#endif //ROGUE_GAMECONTROLLER_H

#include "GameController.h"

GameController::GameController(){
initCommands();
}
void GameController::inputReader() {

while (!gameOver){
string x;
getline(cin,x);
cout << commandReader(&x) << endl;
}

}

string GameController::commandReader(string *inputCommand) {

for (map<string,string>::iterator it = commands.begin(); it!=commands.end(); ++it)
{
if(it->first == *inputCommand)
{
return it->second;
}

}
return "Computer says no type help for commands";
}

void GameController::initCommands() {


commands["end"] = end;
//while attacking
commands["run"] = run;
commands["attack"] = attack;
commands["use potion"] = usePotion;
commands["use item"] = useItem;

//while in room
commands["engage"] = engage;//TODO
commands["search"] = searchRoom;
commands["rest"] = rest;
commands["check bag"] = checkBag;
commands["map"] = checkMap;
commands["stats"] = checkStats;
}

最佳答案

这个问题被标记为 C++11,所以这里有一个使用 unordered_map(一个真正的 HashMap ,不像我的 STL 引用中所说的通常使用二叉搜索树实现的 std::map)和 std::function 的简明示例.

#include <iostream>
#include <functional>
#include <string>
#include <unordered_map>

std::string foo()
{
return "foo!";
}

struct MyClass
{
static std::string bar()
{ return "bar!"; }

std::string FizzBuzz() const
{ return "FizzBuzz!"; }

std::string operator()() const
{ return "Myclass!"; }
};


int main(int argc, char **argv)
{
MyClass mc;

std::unordered_map<std::string, std::function<std::string()>> commands;

commands["myfoo"] = foo;
commands["mybar"] = MyClass::bar;
commands["myfb"] = std::bind(&MyClass::FizzBuzz, mc);
commands["myclass"] = mc;

for( const auto &f : commands)
std::cout << f.second() << std::endl;

std::cout << commands["myfoo"]() << std::endl;

return 0;
}

关于c++ - 我正在尝试制作字符串函数的 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33509425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com