【问题标题】:Simple hashmap implementation in C++C ++中的简单哈希图实现
【发布时间】:2010-09-20 22:34:18
【问题描述】:

我对 C++ 比较陌生。在 Java 中,我很容易实例化和使用 hashmap。我想知道如何在 C++ 中以简单的方式实现它,因为我看到了许多不同的实现,但对我来说它们都不简单。

【问题讨论】:

    标签: c++ hashmap hashtable


    【解决方案1】:

    查看Simple Hash Map (Hash Table) Implementation in C++ 以获得具有通用类型键值对和单独链接策略的基本哈希表。

    【讨论】:

      【解决方案2】:

      大多数编译器应该为你定义std::hash_map;在即将到来的C++0x 标准中,它将作为std::unordered_map 成为标准库的一部分。上面的STL Page 相当标准。如果你使用 Visual Studio,Microsoft 上面有一个页面。

      如果你想使用你的类作为值,而不是作为键,那么你不需要做任何特别的事情。所有原始类型(如intcharbool 甚至char *)都应该作为hash_map 中的键“正常工作”。但是,对于其他任何事情,您都必须定义自己的散列和相等函数,然后编写将它们包装在一个类中的“函子”。

      假设您的课程名为 MyClass 并且您已经定义:

      size_t MyClass::HashValue() const { /* something */ }
      bool MyClass::Equals(const MyClass& other) const { /* something */ }
      

      您需要定义两个仿函数来将这些方法包装在对象中。

      struct MyClassHash {
        size_t operator()(const MyClass& p) const {
          return p.HashValue();
        }
      };
      
      struct MyClassEqual {
        bool operator()(const MyClass& c1, const MyClass& c2) const {
          return c1.Equals(c2);
        }
      };
      

      并将您的 hash_map/hash_set 实例化为:

      hash_map<MyClass, DataType, MyClassHash, MyClassEqual> my_hash_map;
      hash_set<MyClass, MyClassHash, MyClassEqual> my_hash_set;
      

      之后一切都应该按预期工作。

      【讨论】:

      • 我忘了告诉我我使用的是 Unix。您编写的示例看起来很简单,我会尝试一下。但是我应该自己创建 HashValue() 方法,对吧?因为Java有一个Object类的默认hashcode()方法,所以我不知道它在C++中是如何工作的。
      • 我为答案添加了更多解释。此外,boost 的东西也被推荐了——它是类似的,但是学习 boost(的某些部分)就像学习一门全新的语言一样。无序不是一个糟糕的起点。
      【解决方案3】:

      在 C++ 中使用哈希图很容易!这就像使用标准 C++ 映射。您可以使用unordered_map 的编译器/库实现或使用boost 或其他供应商提供的编译器/库实现。这是一个快速示例。如果您点击提供的链接,您会发现更多信息。

      #include <unordered_map>
      #include <string>
      #include <iostream>
      
      int main()
      {
          typedef std::tr1::unordered_map< std::string, int > hashmap;
          hashmap numbers;
      
          numbers["one"] = 1;
          numbers["two"] = 2;
          numbers["three"] = 3;
      
          std::tr1::hash< std::string > hashfunc = numbers.hash_function();
          for( hashmap::const_iterator i = numbers.begin(), e = numbers.end() ; i != e ; ++i ) {
              std::cout << i->first << " -> " << i->second << " (hash = " << hashfunc( i->first ) << ")" << std::endl;
          }
          return 0;
      }
      

      【讨论】:

        【解决方案4】:

        看看boost.unordered,以及它的data structure

        【讨论】:

          【解决方案5】:

          试试 boost 的 unordered 类。

          【讨论】:

            猜你喜欢
            • 2017-12-01
            • 1970-01-01
            • 2020-08-08
            • 2011-01-30
            • 1970-01-01
            • 2012-05-27
            • 2017-03-20
            • 1970-01-01
            相关资源
            最近更新 更多