C++ initialize map of pairs

C++ initialize map of pairs

本文关键字:pairs of map initialize C++      更新时间:2023-10-16

我想静态初始化一个map<string, pair<some_enum, string> >。让我们假设一个从雇员id到职位名称(enum) +名称的映射。

我希望它看起来像这样:

map<string, pair<some_enum, string> > = {
  { "1234a", { BOSS, "Alice" }},
  { "5678b", { SLAVE, "Bob" }},
  { "1111b", { IT_GUY, "Cathy" }},
};

在c++中做到这一点的最好方法是什么?

在c++ 11中,您所拥有的工作得很好(假设您在变量声明中添加了标识符名称)。

在之前的版本中,一种方法是使用一个自由函数来构建映射:

typedef std::map<std::string, std::pair<some_enum, std::string> > map_type;
static map_type create_map()
{
    map_type map;
    map["1234a"] = std::make_pair(BOSS, "Alice");
    map["5678b"] = std::make_pair(SLAVE, "Bob");
    map["1111b"] = std::make_pair(IT_GUY, "Cathy");
    return map;
}
map_type foo = create_map();

或者您可以使用Boost。分配:

std::map<std::string, std::pair<some_enum, std::string> > foo =
    boost::assign::map_list_of("1234a", std::make_pair(BOSS, "Alice"))
                              ("5678b", std::make_pair(SLAVE, "Bob"))
                              ("1111b", std::make_pair(IT_GUY, "Cathy"));

c++ 11的最佳方式:

std::map<string, pair<some_enum, std::string>> my_map = {
  { "1234a", { BOSS, "Alice" }},
  { "5678b", { SLAVE, "Bob" }},
  { "1111b", { IT_GUY, "Cathy" }},
};

就这么简单。

如果不使用boost等外部库,在标准c++ 03中根本不可能实现