Python dict.update() with C++ std::map?

Python dict.update() with C++ std::map?

本文关键字:std map C++ with dict update Python      更新时间:2023-10-16

在Python中,我可以做到这一点:

>>> foo = {1: 10, 2: 20}
>>> foo.update({1: 150, 5: 500})
>>> foo
{1: 150, 2: 20, 5: 500}

如何用std::mapstd::unordered_map在C++中复制相同的内容
可能是一些标准算法

当然,人们可以简单地循环——但这还不够简洁。

std::map::insertstd::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::mapCCD_ 9运算符将插入不存在的元素并替换现有元素。

std::map<int, int> foo {{1,10}, {2,20}};
foo[1] = 150;
foo[5] = 500;

生成的foo包含{1,150}, {2,20}, {5,500}

这适合你的需要吗?