How to use stdext::hash_map?

强颜欢笑 提交于 2019-12-09 10:46:42

问题


I would like to see a simple example of how to override stdext::hash_compare properly, in order to define a new hash function and comparison operator for my own user-defined type. I'm using Visual C++ (2008).


回答1:


This is how you can do it

class MyClass_Hasher {
     const size_t bucket_size = 10; // mean bucket size that the container should try not to exceed
     const size_t min_buckets = (1 << 10); // minimum number of buckets, power of 2, >0
     MyClass_Hasher() {
          // should be default-constructible
     }
     size_t operator()(const MyClass &key) {
             size_t hash_value;
             // do fancy stuff here with hash_value
             // to create the hash value. There's no specific
             // requirement on the value.
             return hash_value;
     }

     bool operator()(const MyClass &left, const MyClass &right) {
            // this should implement a total ordering on MyClass, that is
            // it should return true if "left" precedes "right" in the ordering
     }
 };

Then, you can just use

stdext::hash_map my_map<MyClass, MyValue, MyClass_Hasher>



回答2:


Here you go, example from MSDN




回答3:


I prefer using a non-member function.

The method expained in the Boost documentation article Extending boost::hash for a custom data type seems to work.



来源:https://stackoverflow.com/questions/871838/how-to-use-stdexthash-map

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