Is there any method to find the amount/size of memory allocated to a map in c++? There is a function to find the size of the map,ie,number of entries in the map, but is there any such method for the memory. I have a map ( string, string). The sizeof() is always giving me a size of 48. Any reason why this is so? Thanks :)
util. HashMap. size() method of HashMap class is used to get the size of the map which refers to the number of the key-value pair or mappings in the Map.
A map with 150 million nodes soaked up ~ 15GB, which implies the 8 byte L, 8 byte R, 8 byte int key, and 8 byte datum, totaling 32 bytes, soaked up about 2/3rds of the map's memory for internal nodes, leaving 1/3rd for leaves.
An std::map is typically a self balancing binary search tree1. This is a node-based data structure, quite different to an array. Typically, the data are allocated dynamically.
No, there is not. However you can achieve something similar for classes that support a .size
method such as strings or standard container:
template <class Key, class Value>
unsigned long mapSize(const std::map<Key,Value> &map){
unsigned long size = sizeof(map);
for(typename std::map<Key,Value>::const_iterator it = map.begin(); it != map.end(); ++it){
size += it->first.size();
size += it->second.size();
}
return size;
}
If you want to know the allocated memory you could use .capacity
:
template <class Key, class Value>
unsigned long mapCapacity(const std::map<Key,Value> &map){
unsigned long cap = sizeof(map);
for(typename std::map<Key,Value>::const_iterator it = map.begin(); it != map.end(); ++it){
cap += it->first.capacity();
cap += it->second.capacity();
}
return cap;
}
There is no easy way, but if you really must know (though... why would you?), then you can find out.
All standard library containers by default allocate using a "default allocator" which is not much more than a struct/class with a pair of wrapper functions around new
and delete
(which themselves are, internally, little more than wrappers around malloc
and free
with a little alignment and a type cast on many compilers).
If you are not happy with the default allocator for whatever reason, you can provide a custom allocator to the container template, and it will just seamlessly use that one.
If you write an allocator that increments/decrements an integer at allocation/deallocation, you know how much memory has been dynamically allocated. Add to that the value of sizeof
to be super precise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With