0

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.

1
  • 1
    I think you are stuck with rolling out your own helper function. Standard library map insertion methods do not replace existing elements. Apr 18, 2014 at 19:05

2 Answers 2

4

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}
2
  • 1
    There's a template<class InputIterator> std::{map, unordered_map}::insert(InputIterator, InputIterator) as well.
    – Casey
    Apr 18, 2014 at 18:51
  • 1
    @Casey Thanks. I had to change the whole thing anyway. std::map::insert is not analogous to dict.update. Apr 18, 2014 at 19:14
1

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?

1
  • Actually not, it doesn't quite work with .update() argument stored in a variable. One has to write a loop anyway.
    – ulidtko
    Apr 20, 2014 at 17:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.