Q: Strange sizeof(std::map) I'm using std::map, and can't understand how much memory it consumes.
I have the following map definitions:
CKey {
 long x;
 int y;
 int z;
 bool operator<(const CKey& l) const;
};

CValue {
 int data1;
 int data2;
}

std::map<CKey, CValue> map;
std::cout << "sizeof() = " << sizeof(map) << " Max #Elms = " << map.max_size();

(No mater before or after inserting elements into the map)
I'm getting that.
sizeof() = 48
Max_Size = 329406144173384850



*

*If sizeof(map) = 48, how can it contains 329406144173384850 elements ?

*Does the map save the <CKey,Cvalue> in other memory (heap ?)


A: In C and C++, the sizeof operator tells you how many bytes of stack space an instance of the class will occupy.
Like the other standard containers (except std::array), map allocates its elements on the heap when using the default allocator. This means that its static size (i.e. what sizeof returns) does not depend on the number of elements in the map.
You can find out how many elements are in a map using the size() member function. The max_size() member function on the other hand tells you how many elements the map could theoretically store -- on a 64-bit system, you are almost certainly going to be limited by the amount of RAM on your system rather than what max_size() returns.
Actually working out the total memory use (stack and heap) of a map is not an easy thing to do: in C++17 you might be able to do something like
sizeof(map) + map.size() * sizeof(typename map::node_type);

to give you a rough guess, but really it will depend on the implementation details of your standard library.

A: std::map defines the following methods
max_size()

Returns the maximum number of elements the container is able to hold due to system or library implementation limitations

size()

Returns the number of elements in the container

So, the following calculation will give you a good approximation of the actual size of the map in bytes (Given that the Key and Value types are structs of primitive types):
sizeof(mymap) + mymap.size() * (sizeof(decltype(mymap)::key_type) + sizeof(decltype(mymap)::mapped_type))

