Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map and behavior of already inserted data

Tags:

c++

stl

Does std::map move around already inserted values when inserting new data ?

like image 945
Konstantin Avatar asked Mar 19 '10 12:03

Konstantin


People also ask

Does insert overwrite map C++?

insert() doesn't overwrite.

Does map insert copy or reference?

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.

What is emplace in map?

The map::emplace() is a built-in function in C++ STL which inserts the key and its element in the map container. It effectively increases the container size by one.


2 Answers

The map is implemented as a tree, and when you insert a new element, the tree may need to be rebalanced.

This does not invalidate any iterators or references to elements in the tree. This balancing is done via the manipulation of pointers, so you have nothing to worry about; the nodes themselves stay put.

Balancing involves changing the structure of the tree by telling nodes who their children, parents, and siblings are via re-assigning pointers, but this is an implementation detail. Logically nothing has changed.

like image 72
GManNickG Avatar answered Sep 21 '22 02:09

GManNickG


The standard does not mandate specific implementations of the STL, only the behavior and runtime characteristics. That said, a skip list or tree is a very likely implementation of std::map, so links will be updated, and the relative ordering will change, but the actual data is not going to be moving around.

like image 43
Michael Aaron Safyan Avatar answered Sep 24 '22 02:09

Michael Aaron Safyan