Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map and binary search tree

I have read that std map is implemented using binary search tree data structure.

BST is a sequential data structure (like elements in an array) which stores elements in a BST node and maintains elements in their order. For e.g. if element is less than node, store it in left of node and if it is larger than node, store it in right of node. With this approach, we achieve O(log n) complexity for various operations like search, insert etc.

However, std map is an associate container. We have a key and a value pair to insert. Is it really implemented using BST and, if yes, how? In BST, we don't have any key or value. It is a kind of standard container.

I am little confused. Please help me in providing clarification. Its not affecting my work but I want to understand them better. Thanks for your help.

like image 905
user982740 Avatar asked Aug 24 '14 02:08

user982740


People also ask

Is std::map a binary tree?

As of C++11, there are two1 map types in C++. std::map is based on a binary tree, and std::unordered_map is based on a hash table.

Does a map use a binary search tree?

C++ maps are internally represented as binary search trees. While the standard does not require this, it is implicit in the performance requirements for the data type. Roughly speaking, a binary tree consists of several nodes that obey the following rules: There is a key data type with a total ordering.

Is map in C++ a BST?

The standard map is implemented as a BST so you can perform an in-order traversal of the map in linear time (see: In-order traversal complexity in a binary search tree (using iterators)? ).


2 Answers

A node in a map will generally looks something like this:

struct node
{
    node* left;
    node* right;

    Key_type key;
    Value_type value;
};

You have a general understanding of how a BST works, as you stated:

if element is less than node, store it in left of node and if it is larger than node, store it in right of node.

In the case of my node struct, the "element" is the key member. So keys are compared to determine the organization of the tree. Nodes who's keys compare less than that of a parent node are placed on the left, and nodes who's keys compare greater being placed on the right. The value does not take part in the organization of the tree, it is just supplementary data. It is associated with the key simply by being part of the same struct.

like image 155
Benjamin Lindley Avatar answered Sep 18 '22 16:09

Benjamin Lindley


There's nothing in the C++ standard that dictates how a std::map should be implemented. Consequently, the underlying data structure of a std::map is a decision that has to be taken by the implementer.

Most implementations however, implement std::map as a red-black tree.

like image 29
101010 Avatar answered Sep 19 '22 16:09

101010