1

Once a key value pair is inserted into an unordered_map and let's say iter is pointing to this pair, would &iter->first be unchanged throughout the lifetime of this pair being present in the unordered_map?

The keys would mostly be long strings, so I'd like to store their iterator->first's addresses at other referring places rather than the strings themselves.

vrk001
  • 355
  • 1
  • 2
  • 10
  • Hello PreferenceBean, I went through the link you have posted here. I do see the relevant portion " Unsorted associative containers : unordered_[multi]{set,map}: all iterators invalidated when rehashing occurs, but references unaffected [23.2.5/8]." which does answer my question. Please suggest if any further action is needed from my side w.r.t this post. – vrk001 Feb 19 '16 at 02:38

1 Answers1

2

It will be fine, unless you erase the element directly.

For std::unordered_map::insert,

If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than max_load_factor()*bucket_count().

For std::unordered_map::erase,

References and iterators to the erased elements are invalidated. Other iterators and references are not invalidated.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Yes, I had known that rehashing causing iterators to get invalidated, but are keys also reallocated? Isn't a new iterator allocated pointing to the same key instance in memory which gets returned again as iterator->first? – vrk001 Feb 19 '16 at 02:13
  • @vrk001 My bad. I misunderstood your question. I've modified my answer. – songyuanyao Feb 19 '16 at 02:21