Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize an STL `map` size

Tags:

c++

map

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.

like image 562
MBZ Avatar asked Nov 09 '12 00:11

MBZ


1 Answers

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

like image 165
Evgeny Panasyuk Avatar answered Nov 06 '22 14:11

Evgeny Panasyuk