7

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).

4

3 回答 3

8

这是你可以做到的

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
     }
 };

然后,您可以使用

stdext::hash_map my_map<MyClass, MyValue, MyClass_Hasher>
于 2009-05-16T07:40:20.757 回答
1

给你,来自MSDN的示例

于 2009-05-16T07:38:00.997 回答
0

我更喜欢使用非成员函数。

Boost 文档文章Extending boost::hash for a custom data type中阐述的方法似乎有效。

于 2009-10-16T11:28:36.743 回答