Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning multiple values to std::array in std::map

Tags:

c++

c++11

map

stl

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!

like image 727
Arch1tect Avatar asked Mar 31 '13 21:03

Arch1tect


2 Answers

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.

like image 89
Daniel Frey Avatar answered Sep 28 '22 05:09

Daniel Frey


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.

like image 43
Mike Kinghan Avatar answered Sep 28 '22 05:09

Mike Kinghan