visual-c++ - 如何使用stdext::hash_map?

标签 visual-c++ hashmap

我想看一个如何正确重写 stdext::hash_compare 的简单示例,以便为我自己的用户定义类型定义新的哈希函数和比较运算符。我正在使用 Visual C++ (2008)。

最佳答案

这就是你可以做到的

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>

关于visual-c++ - 如何使用stdext::hash_map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/871838/

相关文章:

c++ - Visual C++ 6 变量作用域错误

c++ - 我能告诉解决方案如何使用 C 编写此格式化数据吗

c++ - 如何从堆中删除变量?

c++ - 获取二进制图像中的值

c++ - 在返回引用的函数上使用 __declspec(nothrow)

java - 通过 Java 中的键聚合文件中的键值行

rust - 为什么 BTreeMap 是可散列的,而不是 HashMap?

hashmap - 如何在使用 java 8 流时将映射键转换为大写?

java - 将新对象存储为 HashMap 的值?

java - (业余程序员)自定义HashMap大小总是比预期小1?