c++ - 在 C++ 中预初始化 map

标签 c++

我需要一个类来拥有从字符串到函数指针的const std::map。如何在不添加如下元素的情况下初始化此 map :

string func1(string a){
    return a;
}

string func2(string x){
    return "This is a random string";
}

//In class declaration:
   const map<string,string(*)(string)> a;

//Where should this go? Any other, probably better method to initialize this map?
    a["GET"] = &func1;
    a["SET"] = &func2;

编辑:

我在 C++11 之前的版本上执行此操作

最佳答案

我在 C++11 之前使用的一种典型方法是创建一个返回映射的函数,并使用该函数初始化我的 const 变量。

#include <algorithm>
#include <iostream>
#include <map>
#include <string>

typedef std::map<std::string, std::string(*)(std::string)> MyMap;

std::string forward(std::string s) { return s; }
std::string backward(std::string s) { std::reverse(s.begin(), s.end()); return s; }

MyMap Init()
{
    MyMap map;
    map["forward"] = &forward;
    map["backward"] = &backward;
    return map;
}

const MyMap Map = Init(); // <--- initialise map via function

int main()
{
    for (MyMap::const_iterator iter = Map.begin(); iter != Map.end(); iter++)
        std::cout << (*iter->second)(iter->first) << "\n";
    return 0;
}

Live example

关于c++ - 在 C++ 中预初始化 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35853325/

相关文章:

c++ - 使用自动递增参数调用宏

C++ switch 语句表达式求值保证

c++ - 使用迭代器删除 vector 中的元素

c++ - 在Windows上构建Linux Docker

c++ - Visual Studio C++ 控制台应用程序生成并运行但不创建 EXE 文件

c++ - 元素乘法——每三个元素

c++ - 对数组中的整数进行排序。但它不适用于某些情况

c++ - std::move 给出了将 std::string 移动到另一个线程的错误

c++ - VS2012 中的 emplace_back 和 shared_ptr vector

c++ - Mex 函数比相同的 C++ 代码更快