从另一个 const std::map 初始化 const std::map 的一部分
initialize part of a const std::map from another const std::map
我有一个 const std::map 初始化如下:
const std::map< int, std::string > firstMap = {
{ 1, "First" },
{ 2, "Second"}
};
然后我想创建另一个 const std::map,它使用第一个映射作为其初始值的一部分,并且还扩展了原始数据。所以我猜它会类似于这个:
const std::map< int, std::string > secondMap = {
{ <firstMap>},
{ 3, "Third"}
};
这样secondMap就有了三对。这可能吗?
编辑:地图也声明为外部。
不,std::map
没有合适的构造函数。但是,您可以做的是使用 lambda 就地初始化变量。
const auto secondMap = [&firstMap] {
std::map<int, std::string> map(firstMap);
map[3] = "Third";
return map;
}();
虽然 完全符合您的需要,但我建议将其提升为一个函数。也许你可以在多个地方使用它。
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;
}
然后使用
const auto secondMap = combine(firstMap,
std::map<int, std::string>{{3, "Third"}});
我有一个 const std::map
const std::map< int, std::string > firstMap = {
{ 1, "First" },
{ 2, "Second"}
};
然后我想创建另一个 const std::map,它使用第一个映射作为其初始值的一部分,并且还扩展了原始数据。所以我猜它会类似于这个:
const std::map< int, std::string > secondMap = {
{ <firstMap>},
{ 3, "Third"}
};
这样secondMap就有了三对。这可能吗?
编辑:地图也声明为外部。
不,std::map
没有合适的构造函数。但是,您可以做的是使用 lambda 就地初始化变量。
const auto secondMap = [&firstMap] {
std::map<int, std::string> map(firstMap);
map[3] = "Third";
return map;
}();
虽然
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;
}
然后使用
const auto secondMap = combine(firstMap,
std::map<int, std::string>{{3, "Third"}});