简体   繁体   中英

will pointer to a variable in the map be invalidated?

I have something in my codes:

class Foo {
// something
};

std::unordered_map<int, Foo> foo_map;
// some insertion on the map

auto iter = foo_map.find(1);
auto foo = &iter->second;  //assume iter!=foo_map.end()
// a lot of operation on the map, may need the rehashing....

So my question is whether the pointer foo is still invalid or not after all this operations?

Mostly, iterators in unordered_map remain valid after insertion/deletion. The only exception being when the growth of the container forces a rehash.

References/pointers to elements remain valid in all cases, even after a rehash.

Have a look at the reference for unordered_map :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM