C++ initialize map of pairs
C++ initialize map of pairs
我想静态初始化一个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中根本不可能实现
相关文章:
- Usages of std::move
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 具有变量Number of Arguments的std::函数的矢量
- Capacity of a deque
- Deprecation of _writeBarrier()
- constexpr begin of a std::array
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- C++ "error: invalid use of void expression"
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- 赛通"Cannot take address of memoryview slice"
- C++ Version Of Double.longBitsToDouble
- 收到错误"invalid use of non-static data member 'stu::n' "
- C++ Usage of AsyncCallback
- 错误:"Left of getValue must have class/struct/union"
- Centos7 g++ "to_string is not in a member of std"
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- 传递 std::vector of std::shared_ptr,而不是更新对象
- C++ initialize map of pairs
- 哪些语言规则允许c++ 11推断出这是一个initializer_list of pairs ?