31

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

4

5 回答 5

26

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

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

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

于 2008-11-05T19:10:50.273 回答
16

在 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;
}
于 2008-11-05T20:09:33.057 回答
7

看看boost.unordered及其数据结构

于 2008-11-05T19:11:26.373 回答
3

试试 boost 的无序类。

于 2008-11-05T19:09:40.870 回答
2

查看C++ 中的简单哈希映射(哈希表)实现,了解具有通用类型键值对和单独链接策略的基本哈希表。

于 2013-05-19T13:32:00.653 回答