Ilyssis
Ilyssis

Reputation: 4949

C++ Multidimensional string array initialization (std::map)

I have this special array of strings in c++:

#include <map>
#include <string>

std::map<std::string, std::map<int, std::string>> oParam;
oParam["pA"][0] = "a";
oParam["pA"][1] = "b";
oParam["pA"][2] = "c";
oParam["pB"][0] = "x";
oParam["pB"][1] = "y";
oParam["pB"][2] = "z";

But I would like to initialize it with an initialization list, something like this:

std::map<std::string, std::map<int, std::string>> oParam{
    { "pA", { "a", "b", "c" } },
    { "pB", { "x", "y", "z" } },
};

But this is giving me an error. Am I missing some brackets?

Upvotes: 2

Views: 512

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490218

If the integers acting as keys in the internal map are going to be contiguous, you could just use a vector instead:

std::map<std::string, std::vector<std::string>> oParam;

With that, the initialization you've given should work.

If you continue to use a std::map instead, you'll have to do a couple of things. First, it supports sparse keys, so you'll need to specify the key for each string you want to insert. Second, you'll need to enclose all the items to insert into one map in braces, something like this:

std::map<std::string, std::map<int, std::string>> oParam {
    { "pA", { { 0, "a" }, { 1, "b" }, { 2, "c" } } },
    { "pB", { { 0, "x" }, { 1, "y" }, { 2, "z" } } }
};

Upvotes: 3

Related Questions