简体   繁体   中英

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)!).

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). 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.

At any rate, map is usually implemented as a red-black tree and tree nodes are on the heap.

(Tree nodes, if I understand correctly, contain instances of value_type , which are key/value pairs of your map).

Note that stack is a bad storage idea for any container as stack should be considered a scarce resource.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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