5

When using std::array I can assign values at one time:

std::array<int, 3> a2 = {1, 2, 3}; 

But I don't know the best way to do it when the above array is combined into a map:

using namespace std;
map <string, array<int, 3>> myMap;

//I'm doing it like below now...

array<int, 3> tempArray = {1,2,3}; // can I save this line somehow?
myMap[myString] = tempArray;

Please also let me know if this is actually the right way. Thanks!

2 Answers 2

4

While using insert as shown in the other answer is more efficient, you can also use

myMap["foo"] = {{1,2,3}};

if concise code is more important to you.

Sign up to request clarification or add additional context in comments.

1 Comment

@ShmilTheCat The question is about C++11 and doesn't indicate the need for a specific compiler. It works with GCC 4.6.3, GCC 4.7.2, GCC 4.8.0 and Clang 3.2. It's standard-conforming C++11.
2

You can save a line (though not many characters) like this:

myMap.insert(std::make_pair(myString,array<int,3>{{1,2,3}}));

BTW, according to GCC 4.7.2 you are missing a pair of braces around the initializer for tempArray

However this will not modify the mapped value for myString if it happens already to exist.

And if and when you have a library that has std::map::emplace you can save more characters.

4 Comments

I believe it should compile as c+11, as tagged. It compiles under gcc 4.7.2, clang-3.2 and intel c++ 2013.2
The extent of c++11 support in MSVC++ 2012 is shown here: msdn.microsoft.com/en-gb/library/vstudio/hh567368.aspx. It does not support initializer lists, among much else.
@ShmilTheCat And here's a good comparison chart for C++11 feature support in VC 2012 Nov CTP, GCC 4.8, Clang 3.3 and Intel 13 compiler. That said: Have you installed and enabled CTP?
@DanielFrey msvc++ 2012 novemer ctp does support initializer lists in user code but the special constructors / inserters for standard containers haven't been implemented yet, but will be in the rtm version.

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.