views:

53

answers:

2

Hi,

I've a hash table defined like this

typedef std::unordered_map<unsigned long long int,unsigned long long int> table_map;

and in the program, I read the contents of the a file into a buffer using fread like this:

fread(buffer, sizeof(long long int), 1024, file1);

I declare the hash table as

table_map c1;

Now i create a hash table like

for (i = 0; i < 1024; i++)
    c1.insert(table_map::value_type(buffer[i], i));

Now my questions is, after the for loop how can I get the size of the hash table?

It has 1024 elemts of type unsigned long long int and also the keys of the same type but I could not use sizeof(Mymap) or `size of(c1) beacause its just returning the value 32. Is there any way to find it?

Thanks, Sunil

+2  A: 

All of the standard library containers have a size() member function that returns the number of elements in the container.

You can simply call c1.size().

James McNellis
Works perfect. But how do I relate it with the total size? I mean the size of the hash table includes the number of elements (in my case each element is unsigned long long int) and size of the key (which is also unsigned long long int) right?
Sunil
@Sunil: If you want the size _in bytes_, then there is no portable way to get that information.
James McNellis
@James McNellis, Sunil: Would you have any better luck if you used a custom allocator? It seems the allocator is only for pairs, not for the dynamically allocated bookkeeping data. That seems to break *some* scenarios that could otherwise be handled with a custom allocator, though.
Merlyn Morgan-Graham
@ merlyn Morgan-Graham: Custom allocator for a hash table? I've used custom allocators like vectors instead of arrays but I've not used anything with respect to hash table because I'm new to C++. Can you throw more light on it or share any link where i could learn about what you are suggesting? thanks.
Sunil
@Sunil: To get the size of its contents in bytes, multiply `c1.size() * sizeof( table_map::value_type )`. However, this doesn't represent the total memory overhead.
Potatoswatter
+2  A: 

Multiply the container's size property by the size of a pair:

std::cout << c1.size() * sizeof(table_map::value_type) << "\n";

On my system, this prints out:

16384

This is not totally accurate, because the bookkeeping data isn't accounted for. You cannot account for it, because (as far as I know) the standard doesn't have any guarantees about that implementation detail.

You may get slightly better data if you examine the bucket data. ::bucket, :: bucket_count, ::bucket_size. This may only give you data about keys, values, and pairs though. I haven't tried it.

Merlyn Morgan-Graham
Thank you. That was helpful.
Sunil