What data structure is inside std::map in C++?

前端 未结 6 923
余生分开走
余生分开走 2020-12-03 11:34

I\'m beginner and learning C++ Having hard times to understand std::map concepts, because the code I\'m playing with implies that the map is a search tree, i.e.

6条回答
  •  醉酒成梦
    2020-12-03 11:56

    Viewed externally a map is just an associative container: it behave externally as an "array" (supports an a[x] expression) where x can be whatever type (not necessarily integer) is "comparable by <" (hence ordered).

    But:

    • Because x can be any value, it cannot be a plain array (otherwise it must support whatever index value: if you assign a[1] and a[100] you need also the 2..99 elements in the middle)
    • Because it has to to be fast in insert and find at whatever position, it cannot be a "linear" structure (otherwise elements shold be shifted, and finding must be sequential, and the requirements are "less then proportional finding time".

    The most common implementation uses internally a self-balancing tree (each node is a key/value pair, and are linked togheter so that the left side has lower keys, and the right side has higer keys, so that seraching is re-conducted to a binary search), a multi-skip-list (fastest than tree in retrieval, slower in insert) or a hash-based table (where each x value is re-conducted to an index of an array)

提交回复
热议问题