gpt4 book ai didi

c++ - 如何使用 Visual Studio 2008 将字符串映射到函数?

转载 作者:行者123 更新时间:2023-12-01 22:41:30 27 4
gpt4 key购买 nike

此问题引用了以下问题: Using a STL map of function pointers

在 C++11 中,我使用映射来存储 <string, function>配对可以更有效地执行代码,而不是使用 if...else if...else if如引用链接所述。

代码封装在成员函数中,其中 this引用类,允许访问成员变量。

using f = std::function<void()>;
static const std::map<std::string, f> doSumthin{
{"case 1", [this]() {
// execute code in case 1
}},
{"case 2", [this]() {
// execute code in case 2
}},

};

auto it = doSumthin.find(someString);

if (it != doSumthin.end())
{
it->second();
}

但是,我需要使代码库在 VS 2008 中工作。我不确定实现复制上述代码以在 VS 2008 中工作而不恢复到效率较低的最佳方式是什么 if...else if .

我可以获得有关此问题的一些指导吗?

最佳答案

#include <map>
#include <string>

typedef void (*func_ptr_type)();

void func_case_1() {}
void func_case_2() {}

static std::map<std::string, func_ptr_type> doSumthin;

void initMap()
{
doSumthin["case 1"] = func_case_1;
doSumthin["case 2"] = func_case_2;
}

int main()
{
initMap();

std::map<std::string, func_ptr_type>::iterator it = doSumthin.find("case 1");
if (it != doSumthin.end())
{
it->second();
}
return 0;
}

关于c++ - 如何使用 Visual Studio 2008 将字符串映射到函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59658175/

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