简体   繁体   English

std :: map和二叉搜索树

[英]std::map and binary search tree

I have read that std map is implemented using binary search tree data structure. 我已经读过std map是使用二叉搜索树数据结构实现的。

BST is a sequential data structure (like elements in an array) which stores elements in a BST node and maintains elements in their order. BST是一种顺序数据结构(类似于数组中的元素),它将元素存储在BST节点中并按顺序维护元素。 For eg 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. 例如,如果element小于node,则将其存储在节点的左侧,如果它大于node,则将其存储在节点的右侧。 With this approach, we achieve O(log n) complexity for various operations like search, insert etc. 通过这种方法,我们实现了搜索,插入等各种操作的O(log n)复杂度。

However, std map is an associate container. 但是,std map是一个关联容器。 We have a key and a value pair to insert. 我们有一个键和值插入。 Is it really implemented using BST and, if yes, how? 它是否真的使用BST实现,如果是,如何实现? In BST, we don't have any key or value. 在BST,我们没有任何关键或价值。 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. 谢谢你的帮助。

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: 如您所述,您对BST的工作原理有一般性的了解:

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. 如果element小于node,则将其存储在节点的左侧,如果它大于node,则将其存储在node的右侧。

In the case of my node struct, the "element" is the key member. 在我的node结构的情况下,“元素”是key成员。 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. value不参与树的组织,它只是补充数据。 It is associated with the key simply by being part of the same struct. 它只是通过成为同一结构的一部分而与键相关联。

There's nothing in the C++ standard that dictates how a std::map should be implemented. C ++标准中没有任何内容规定如何实现std::map Consequently, the underlying data structure of a std::map is a decision that has to be taken by the implementer. 因此, std::map的底层数据结构是实现者必须采取的决策。

Most implementations however, implement std::map as a red-black tree. 但是,大多数实现都将std::map实现为红黑树。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM