简体   繁体   中英

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

In Python, I can do this:

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

How to replicate the same in C++ with std::map or std::unordered_map ?
Some standard algorithm maybe?

Off course, one can roll a straightforward loop — but that's not succinct enough.

There are std::map::insert and std::unordered_map::insert overloads that take an std::initializer_list and offer a similar functionality. But these only to up-date non-existing elements.

To replicate the dict.update behaviour, you could roll out your own helper function:

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";
}

Output:

{1, 150}
{2, 20}
{5, 500}

You could use the [] operator for std::map the [] operator will insert non-existing elements and replace existing elements.

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

The resulting foo contains {1,150}, {2,20}, {5,500}

Would this suit your needs?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM