What is the most efficient way to update the array values of an unordered_map for a specific key?

Viewed 36

Consider the following unordered maps

#include <array>
#include <string>
#include <unordered_map>

int main()
{
    std::unordered_map<std::string, int> str2int { 
        {"key1", 1},
        {"key2", 2}
    };
    str2int["key1"]++;
    str2int["key3"] = 5;

    std::unordered_map<std::string, std::array<int, 2>> str2arr { 
        {"key1", {1,2}},
        {"key2", {3,4}}
    };
}

Updating the values of str2int is straightforward as seen above. What is the most efficient and cleanest value assignment method for the unordered_map str2arr for a given (existing or new) key?

1 Answers

You may be looking for a compound literal if you want to add a new std::array value to the map.

str2arr["key3"] = (std::array<int, 2>){ 5, 6 };

Suggested reading on the lifetime implications of using this in C++.

Related