简体   繁体   中英

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

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM