std::map iterators

J

jason.cipriani

In an std::map, iterators do not become invalid if other elements are
added erased. Just to make sure, does that mean that in the following
code:

map<string,B> m;
B *b = &(m["something"]);

The address in 'b' will remain valid, and always point to that same
object, as long as that data isn't erased from the map?

Similarily:

map<string,B> m;
map<string,B>::iterator i(m.find("something"));
B *b = (i == m.end()) ? NULL : &((*i).second);

Will b there also always remain valid as long as "something" remains
in the map?

Thanks,
Jason
 
F

Frank Birbacher

Hi!

The address in 'b' will remain valid, and always point to that same
object, as long as that data isn't erased from the map?
Yes.

Will b there also always remain valid as long as "something" remains
in the map?

Yes.

Regards,
Frank
 
K

Kai-Uwe Bux

In an std::map, iterators do not become invalid if other elements are
added erased. Just to make sure, does that mean that in the following
code:

map<string,B> m;
B *b = &(m["something"]);

The address in 'b' will remain valid, and always point to that same
object, as long as that data isn't erased from the map?

Formally, validity of iterators and references into a map are separate
issues.

However, you are lucky: the standard also guarantees that references into a
map remain valid. Now, one could argue that reference validity does not
imply pointer validity. However, I think that is a little stretch. So 'b'
will remain valid. If you want to be on the formally safe side, you could
do something like:

B& b = m["something"];

Similarily:

map<string,B> m;
map<string,B>::iterator i(m.find("something"));
B *b = (i == m.end()) ? NULL : &((*i).second);

Will b there also always remain valid as long as "something" remains
in the map?

With the caveats from above: yes.


Best

Kai-Uwe Bux
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top