Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the STL map container optimized (balanced tree) while constructed?

Tags:

c++

map

stl

If I insert an ordered (increasing) sequence of elements into a map, will the final binary tree be somehow optimized? Or will every element have a child "to it's right"? That would make such a tree very inefficient, since then the lookup would be linear.

I couldn't find any detailed information about the insertion process into STL map.

like image 642
HWende Avatar asked Nov 28 '22 17:11

HWende


2 Answers

The C++11 standard (23.1) mandates logarithmic complexity for both insert and find for associative containers. Constructing them from two iterators i and j such that [i, j) denotes a suitably sorted range of values is even required to have linear time complexity. Whether that means that "the final binary tree is optimized", or whether maps are binary trees at all, is left unspecified.

In practice, though, std::set, std::map and their multi-friends are virtually always red-black trees, since that's what the original HP/SGI reference implementation of the STL had, and all modern C++ libraries that I know derive from that implementation.

like image 96
Fred Foo Avatar answered Dec 19 '22 06:12

Fred Foo


In general, a std::map is implemented using a red-black tree, which is self-balancing. So yes, it's optimized.

If you insert ordered data, the self-balancing will probably take less, since swaps between nodes will not be that frequent.

like image 42
Luchian Grigore Avatar answered Dec 19 '22 04:12

Luchian Grigore