24

I have the following code:

std::unordered_map<std::string, std::string> map;

map["k1"] = "v1";
auto& v1 = map["k1"];
map["k2"] = "v2";

After reading https://en.cppreference.com/w/cpp/container/unordered_map#Notes

Notes

The swap functions do not invalidate any of the iterators inside the container, but they do invalidate the iterator marking the end of the swap region.

References and pointers to either key or data stored in the container are only invalidated by erasing that element, even when the corresponding iterator is invalidated.

It looks like v1 can be safely used after inserting new values, even if re-hashing might occur during insertion.

Is my interpretation of this quote correct? May I use references/pointers of the values from the map after modifying the map (obviously erasing the value itself would invalidate the reference/pointer)?

1
  • 3
    Yes, you're correct. See here too.
    – Ami Tavory
    Commented Oct 5, 2016 at 8:16

1 Answer 1

24

It looks like v1 can be safely used after inserting new values, even if re-hashing might occur during insertion.

Yes, std::unordered_map::operator[] doesn't invalidate references, even rehashing happens.

(emphasis mine)

If an insertion occurs and results in a rehashing of the container, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated.

From the standard, [unord.req]/9:

(emphasis mine)

Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements.

4
  • stackoverflow.com/questions/39868640/… If rehashing occurs (due to the insertion), all iterators and references are invalidated Commented Aug 30, 2023 at 21:13
  • @QingchuanZhang You mean my quotes from cppreference.com and standard are wrong? Commented Aug 31, 2023 at 1:58
  • I feel they are conflicting, cppreference says If rehashing occurs (due to the insertion), all iterators and references are invalidated and the standard says Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements Commented Aug 31, 2023 at 16:16
  • @QingchuanZhang The standard is always correct. cppreference.com is just a wiki-based website. Commented Sep 1, 2023 at 0:49

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.