Python dict.update() with C++ std::map?
Python dict.update() with C++ std::map?
在Python中,我可以做到这一点:
>>> foo = {1: 10, 2: 20}
>>> foo.update({1: 150, 5: 500})
>>> foo
{1: 150, 2: 20, 5: 500}
如何用std::map
或std::unordered_map
在C++中复制相同的内容
可能是一些标准算法?
当然,人们可以简单地循环——但这还不够简洁。
有std::map::insert
和std::unordered_map::insert
重载采用std::initializer_list
并提供类似的功能。但这些只是最新的不存在的元素。
要复制dict.update
行为,您可以推出自己的助手功能:
template <typename K, typename V>
void update_map(std::map<K,V>& m,
std::initializer_list<typename std::map<K,V>::value_type> l)
{
for (const auto& p : l)
m[p.first] = p.second;
}
std::map<int, int> m { {1, 10}, {2, 20} };
update_map(m, {{1, 150}, {5, 500}});
for (const auto& p : m)
{
std::cout << "{" << p.first << ", " << p.second << "}n";
}
输出:
{1, 150}
{2, 20}
{5, 500}
您可以将[]
运算符用于std::map
CCD_ 9运算符将插入不存在的元素并替换现有元素。
std::map<int, int> foo {{1,10}, {2,20}};
foo[1] = 150;
foo[5] = 500;
生成的foo包含{1,150}, {2,20}, {5,500}
这适合你的需要吗?
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 使用一个考虑到std::map中键值的滚动或换行的键
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- C++如何创建 std::map
- 从其他容器中移动构造"std::map"
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- C++中 std::map 的运行时复杂度是多少?
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 使用重载 [] 运算符返回 std::map() 的可赋值
- std::map, std::unordered_map - 缩小初始值设定项列表中的转换范围
- C++ 使用枚举类对象分配 std::map 值
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- std::map:当元素不可默认构造时创建/替换元素
- Arduino编译器和STL:使用std::vector和std::map