Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map, pointer to map key value, is this possible?

std::map<std::string, std::string> myMap;  std::map<std::string, std::string>::iterator i = m_myMap.find(some_key_string); if(i == m_imagesMap.end())     return NULL;  string *p = &i->first; 

Is the last line valid? I want to store this pointer p somewhere else, will it be valid for the whole program life? But what will happen if I add some more elements to this map (with other unique keys) or remove some other keys, won’t it reallocate this string (key-value pair), so the p will become invalid?

like image 428
michael Avatar asked Feb 05 '09 14:02

michael


1 Answers

Section 23.1.2#8 (associative container requirements):

The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.

So yes storing pointers to data members of a map element is guaranteed to be valid, unless you remove that element.

like image 127
Greg Rogers Avatar answered Sep 22 '22 11:09

Greg Rogers