Reputation: 583
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.
Upvotes: 5
Views: 444
Reputation: 206577
While @Rakete111's answer is perfectly valid for what you need, I suggest elevating that to a function. Maybe you can use it multiple places.
std::map<int, std:::string> combine(std::map<int, std::string> const& map1,
std::map<int, std::string> const& map2)
{
std::map<int, std:::string> res(map1);
res.insert(map2.begin(), map2.end());
return res;
}
and then use
const auto secondMap = combine(firstMap,
std::map<int, std::string>{{3, "Third"}});
Upvotes: 5
Reputation: 48948
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;
}();
Upvotes: 9