Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize part of a const std::map from another const std::map

I have a const std::map< int, std::string> initialized like so:

const std::map< int, std::string > firstMap = {
    { 1, "First" },
    { 2, "Second"}
};

Then I want to make another const std::map which uses the first map as part of its initial values and also has extends the original data. So it would be something similar to this I guess:

const std::map< int, std::string > secondMap = {
    { <firstMap>},
    { 3, "Third"}
};

so that the secondMap has the three pairs. Is this possible?

EDIT: Also the maps are declared extern.

like image 741
dmoody256 Avatar asked Dec 13 '22 16:12

dmoody256


1 Answers

No, std::map doesn't have the right constructor for this. What you can do however is use a lambda to initialize the variable in place.

const auto secondMap = [&firstMap] {
    std::map<int, std::string> map(firstMap);
    map[3] = "Third";
    return map;
}();
like image 128
Rakete1111 Avatar answered Dec 25 '22 22:12

Rakete1111