简体   繁体   English

如何分配STL地图?堆栈还是堆?

[英]How is a STL map allocated? Stack or Heap?

我想知道c ++中的STL map是否具有连续的内存 - 还是分配给堆的内存?

Since map is a dynamic container , the memory for its elements is dynamically allocated (whatever that means (it depends on a configurable allocator)!). 由于map是一个动态容器 ,因此动态分配其元素的内存(无论这意味着什么(它取决于可配置的分配器)!)。

Moreover, map is a node-based container, so each element goes into a distinct, separate allocation (so as to permit maximal iterator and reference non-invalidation). 而且, map是一个基于节点的容器,因此每个元素都进入一个不同的独立分配(以便允许最大迭代器和引用非失效)。 Elements are almost certainly not contiguous in memory, and probably scattered about in a way that reflects how you added them. 元素几乎肯定不会在内存中连续,并且可能以反映您添加它们的方式分散。

Practically, a map will be implemented as some type of balanced tree in order to achieve logarithmic lookup, insertion and deletion times. 实际上,地图将被实现为某种类型的平衡树,以实现对数查找,插入和删除时间。

(If you want a data structure with contiguous storage and logarithmic lookup time, consider a sorted vector.) (如果您希望数据结构具有连续的存储和对数查找时间,请考虑已排序的向量。)

It is more than likely implementation-specific, and y ou can certainly change the allocator of any STL container , but this is not for the faint of heart and you would need to look at the documentation for the standard library you are using. 它很可能是特定于实现的,并且您当然可以更改任何STL容器的分配器 ,但这不适合胆小的人,您需要查看您正在使用的标准库的文档。

At any rate, map is usually implemented as a red-black tree and tree nodes are on the heap. 无论如何,map通常实现为红黑树 ,树节点在堆上。

(Tree nodes, if I understand correctly, contain instances of value_type , which are key/value pairs of your map). (如果我理解正确,树节点包含value_type的实例 ,它们是地图的键/值对)。

Note that stack is a bad storage idea for any container as stack should be considered a scarce resource. 请注意,堆栈对于任何容器都是一个糟糕的存储理念,因为堆栈应该被视为稀缺资源。

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

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