C++ unordered_map with char* as key

前端 未结 3 1177
無奈伤痛
無奈伤痛 2020-12-10 05:12

I feel exhausted when trying to use the container unordered_map with char* as the key (on Windows, I am using VS 2010). I know that I have to defin

3条回答
  •  生来不讨喜
    2020-12-10 05:44

    You comparator is fine (although passing a nullptr is undefined and probably should be handled)

    The hash, ::std::tr1::hash is hashing off pointers so each "abc" goes (usually) in a different bucket

    You need to write your own hash function that guarantees that hash("abc") always gives the same answer

    For now - performance will be terrible, but have a hash that returns 0 - and you should see the second "abc" match the first

    As per comments - using std::string simplifies memory management and provides a library supported hash and comparator, so just std::unordered_map will work. This also means that upon deletion of the unordered map all strings will be deallocated for you. You can even instantiate the std::strings from char arrays on the stack safely.

    If you still want to use char * then you will still need your own comparator and hash, but you can use std::shared_ptr to manage the memory for you (do not use stack instances - do a new char[]) you will then have a std::unordered_map, X> but have no complications later from memory leaks.

    If you still want to use char * you are on the right track, but it is important that you use a memory leak tool like purify or valgrind to make sure that you truly have all the memory management under control. (This is generally a good idea for any project)

    Finally, global variables should be avoided.

提交回复
热议问题