unordered_map for heap management system. Is a no-collision setup possible?

£可爱£侵袭症+ 提交于 2019-12-08 10:52:16

问题


The unordered_map<> (c++11) uses a hash function to internally organize it's key-values. The collision probability is very small (1.f/std:numeric_limits<size_t>::max()).

Is it okay to use an unordered_map<> as a storage container for a heap memory management? That is, if two elements get mixed up (by collision) the stability of the program is destroyed. In my case that would lead to repeatedly calling free() on the same pointer. (SIGSEGV).

Or is the collision probability only important when searching for a key. And it is guaranteed that two different keys always refer to different values?

Follow up question: Say the unordered_map with its standard hash function is not okay for my application. If one wanted to make sure that no collision can occur, and one can limit oneself to a maximum of size_t elements, can one provide her own hash function that returns the argument itself. Something like:

template<class T>
struct Hash
{
  size_t operator()(T t) {
    return (size_t)t;
  }
}

and be sure of no collisions?


回答1:


Collisions only affect performance, not the contents of the container. unordered_map takes a hash function and an equality function. Two elements can safely have the same hash, and if they compare non-equal then they're treated as non-equal. They'll just always be in the same hash bucket. Large buckets harm performance of operations that look in that bucket.



来源:https://stackoverflow.com/questions/10751527/unordered-map-for-heap-management-system-is-a-no-collision-setup-possible

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