简体   繁体   中英

initialize an STL `map` size

is it possible to initialize an STL map size?

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

There are several options:

  • You may try to use map with statefull allocator. For instance from Boost.Container or from C++11. Or if you accept limitations of non-statefull allocators, then you could even use map from C++98/03.

  • Consider to use unordered_map (again from Boost or from C++11) - it takes buckets count as constructor parameter. It differs from map, in that it is based on hashing rather than on strict weak ordering.

  • Another option is flat_map from Boost . It has reserve member function. Description of flat map/set:

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

  • Or, if boost is not available - then you could simply use std::vector + std::sort + std::lower_bound (or wrap them to small flat_map like class). Ie just put your elements to vector (unordered), then sort it, and then - when you need to query element by key - just use lower_bound.

Which choice is better - depends on your usage patterns.

You can't. It's a tree (usually a red-black tree). The actual values are going to determine memory layout.

However , you can

  • use Boost Intrusive maps (which use elements you allocated in another container, like a vector), decorated with 'hooks' to implement the map functionality over it

  • use std::map with allocators, so you can allocate all the actual elements from a fixed 'pool' (memory region)

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

reserve can be emulated by rehash as in Table 103 in N3376 .

a.rehash(n) 
Post: a.bucket_count() > a.size() / a.max_load_factor() 
      and a.bucket_count() >= n.

a.reserve(n) Same as a.rehash(ceil(n / a.max_load_factor()))

Source

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