Alexander Vassilev
Alexander Vassilev

Reputation: 1439

unordered_map of iterators - how to check uninitialized elements

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?

Upvotes: 1

Views: 951

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476990

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.

Upvotes: 3

Related Questions