Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store pointer to map key

Tags:

c++

c++11

std::map<Key,Value> mymap;
(void)mymap[Key(...)]; // create value if not there
typename std::map<Key,Value>::iterator it = mymap.find(key);
it->second.pkey = &it->first; // store a pointer to the actual key

Is this safe? In other words, is map allowed to copy the key around during insert/erase operations, which would invalidate Value::pkey?

Any C++98 vs C++11 differences on this?

like image 778
Irfy Avatar asked Aug 26 '26 06:08

Irfy


1 Answers

std::map iterators are only invalidated on erasure (erase or clear). Inserting new elements into the map doesn't affect existing iterators. This is the same in C++98 and C++11.

If an iterator remains valid it follows that the key it points to also remains valid.

like image 160
Jonathan Potter Avatar answered Aug 28 '26 21:08

Jonathan Potter