Initialize card size "STL"

Is it possible to initialize the size of an STL map ?

I know how many elements will be on my map at the end, and I want to allocate all the necessary memory at the very beginning.

+8
c ++ map
source share
4 answers

There are several options:

  • You can try to use a map with statefull allocator. For example, from Boost.Container or from C ++ 11. Or, if you accept the limitations of non-stationary distributors, then you can even use a map from C ++ 98/03.

  • Suppose to use unordered_map (again from Boost or from C ++ 11) - it takes the number of buckets as a constructor parameter. It differs from a card in that it is based on hashing, and not on a strict weak order.

  • Another option is flat_map from Boost . It has the function to reserve . Description of flat card / set:

Boost.Container flat_ [multi] map / set container are ordered vector associative containers based on Austern and Alexandrescu guidelines.

  • Or, if boost is not available, you can simply use std :: vector + std :: sort + std :: lower_bound (or bind them to the small flat_map class). That is, just put your elements in a vector (unordered), then sort it, and then - when you need to request an element by key - just use lower_bound.

Which choice is best depends on your usage patterns.

+6
source share

You can not. This is a tree (usually a red-black tree). Actual values ​​will determine the memory location.

However , you can

  • use the Customize intrusive cards (which use elements that you selected in another container, for example, a vector) decorated with “hooks” to implement the functionality of the card above it

  • use std :: map with allocators, so you can select all the actual elements from a fixed "pool" (memory area)

+4
source share

The only thing I can think of is to use its iterator constructors. The only trick is that then you need to create another container with the size you need and give it to the iterators of the constructor.

+1
source share

reserve can be emulated using rehash , as in table 103, in N3376 .

 a.rehash(n) Post: a.bucket_count() > a.size() / a.max_load_factor() and a.bucket_count() >= nareserve(n) Same as a.rehash(ceil(n / a.max_load_factor())) 

A source

0
source share

All Articles