Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map: can it copy and move keys after they have been inserted?

In other words, is it safe to store pointers to keys from a map? Or is it possible for the map to copy and move keys during its lifetime, thus invalidating existing pointers?

The docs say: "Iterator validity: No changes." Does that mean the answer to my question is "no, they cannot be copied or moved"?

like image 771
Chris Avatar asked Feb 21 '16 19:02

Chris


People also ask

Does std::map insert make copy?

Yes -- when you insert an item into an std::map, you pass it by value, so what it contains is a copy of what you passed.

Can a std::map have duplicate keys?

Duplicate keys are not allowed in a map : map insert « map multimap « C++ Tutorial. 23.6. 1. Insert characters into map.

Can a map hold duplicate keys C++?

a map will not throw any compile/run time error while inserting value using duplicate key. but while inserting, using the duplicate key it will not insert a new value, it will return the same exiting value only. it will not overwrite.

Does insert overwrite map C++?

insert() doesn't overwrite. New! Save questions or answers and organize your favorite content. Learn more.


1 Answers

The std::map container template provides a node-based container, which means that iterators and references to a container element are never invalidated until the element is erased from the map. So you can hand out element key addresses to third parties as long as the map is alive and the element remains within it.

like image 133
Kerrek SB Avatar answered Nov 04 '22 08:11

Kerrek SB