开发者

How is a map of STRING (to integer or anything) stored internally? How are they ordered/balanced?

开发者 https://www.devze.com 2023-03-17 03:20 出处:网络
I know that the Map container in STL 开发者_运维百科is internally a Red-Black Tree, which is a self-balancing tree.

I know that the Map container in STL 开发者_运维百科is internally a Red-Black Tree, which is a self-balancing tree.

In Map, the lowest element is at the top of the tree. So, for a map of integer to 'anything', the lowest integer will be at the top and so on. It always balances itself. That's why we get a log n complexity while searching for an integer and its associated value.

But in case of map of string to 'anything', how does it balances and orders itself, if it does? Which string would be at the top of the tree? Does it matches the ASCII values or something?

This might be lame, but I need to know this as I have to ensure that I am adhering to the complexity of log n in my code.


In Map, the lowest element is at the top of the tree.

No, the least element is at the left-most node, the one you reach by following the left child pointer until it's null. In the case of strings, the least element is the one that always compared "less than" all the other strings you've inserted into the map. The default comparison is lexicographic.

The balancing proceeds as usual, by a bunch of pointer swaps. The path from the root to any leaf is guaranteed to have length Θ(lg n), no matter what.

(This is assuming the original STL implementation of map, which is still common, though a conforming C++ library might use a different structure.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号