2

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?

1 Answer 1

3

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" } } }
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thx for the vector solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.