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