1

I want to statically initialize a map<string, pair<some_enum, string> >. Let's say a map from employee id to job title (enum) + name.

I would love for it to look like this:

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

What is the best way to do this in C++?

cdhowie
  • 158,093
  • 24
  • 286
  • 300
user3757652
  • 35
  • 1
  • 2
  • 6

2 Answers2

7

The best way in C++11:

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

It's that easy.

It's not possible at all in standard C++03 without using external libraries like boost.

cubuspl42
  • 7,833
  • 4
  • 41
  • 65
  • 1
    C++03 isn't *too* bad. Something like `boost::whatever_map_list_of("1234a", std::make_pair(BOSS, "Alice"))("5678b", …)` – chris Aug 22 '14 at 18:13
  • Hmm, I was thinking about standard C++. I'll let other talk about boost, because I don't have much experience with it. – cubuspl42 Aug 22 '14 at 18:15
7

In C++11, what you have works fine (assuming you add an identifier name to the variable declaration).

In versions prior, one approach would be to have a free function that builds the map:

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();

Or you can make use of Boost.Assign:

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"));
cdhowie
  • 158,093
  • 24
  • 286
  • 300