Map and multimap : memory usage / management differences?

佐手、 提交于 2019-12-11 09:07:30

问题


I wrote a program that have to read a big file with operator>> , count some stuff and insert datas (string and int) in a multimap. The problem is that the program crashes and it seems to be a memory problem (it works well with small files). I think that it reaches the memory allocation limit of Windows.

What I tried : I made a 32-bit and an 64-bit versions. As you know, Windows has a memory allocation limit that is not the same for 32bits and 64bits builds. With both it crashes. I looked the performance tab of the task manager to observe the memory consumption. 32-bit : the program crashes every time it reaches 5.3 GB. 64-bit : the memory consumption of the program continually increases until it reaches the whole RAM of the system and crashes.

I tried with a map instead of a multimap : the program never crashes and stay stable at roughly 3.5 GB (32-bit and 64-bit builds) all along the program execution.

So, do you know if there is a difference between map and multimap in terms of memory usage or memory management ? Or is it just because map do not allows duplicate keys ?


回答1:


Of course there is. Did you read descriptions?

std::map:

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare.

std::map::insert:

Return value: 1-2) Returns a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a bool denoting whether the insertion took place.

You cannot have two same keys, so you overwrite values under the same key, you don't allocate any new space.

std::multimap:

Multimap is an associative container that contains a sorted list of key-value pairs.

std::multimap::insert cannot "fail", it always return an iterator because, it always adds new association. So adding items under the same key in a loop will allocate new memory.

Similar is true for every multi-container (set, unordered map, etc.). They are semantically different.



来源:https://stackoverflow.com/questions/29229492/map-and-multimap-memory-usage-management-differences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!