1

I have an unordered_map<string, list<SomeClass>::iterator>

I want to insert an element in this map, but only if it does not exist already. If it exists, I don't want to overwrite the existing item. Also, I want to avoid doing two lookups to check if the item exists and then for the insert. I came to the conclusion that I should use operator[] to get an element with the key, check if it is valid, and if not, initialize it. The problem is that the element is an iterator, and I have to check if it is initialized, which is not really possible. I can use a class that derives from teh list iterator class, and implement the defautl constructor to initialize it to an 'invalid' value, but in the constructor I don't have access to the list instance to get its end() iterator. Any ideas how to do it?

1 Answer 1

3

Use insert or emplace, which won't overwrite the value if it already exists:

auto i = m.insert(std::make_pair("hello"), my_iterator);
auto j = m.emplace("hello", my_iterator);                  // same

You can test i.second to see whether the insertion succeeded or not, and i.first is an iterator to the map element.

2
  • Ha! Call me stupid, but I always thought that insert overwrites the value :) Dec 5, 2012 at 10:05
  • 2
    @AlexanderVassilev From this reference for insert: "Inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key." Dec 5, 2012 at 10:09

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.