在C ++中简单的hashmap实现 [英] Simple hashmap implementation in C++

查看:748
本文介绍了在C ++中简单的hashmap实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手。在Java中,我很容易实例化和使用一个hashmap。我想知道如何以一种简单的方式在C ++中做,因为我看到许多不同的实现,没有一个看起来很简单。

解决方案

大多数编译器应为你定义 std :: hash_map C ++ 0x 标准中,它将是标准库的一部分,因为 std :: unordered_map STL Page 是相当标准的。如果您使用Visual Studio, Microsoft 上有一个页面。 / p>

如果你想使用你的类作为值,而不是键,那么你不需要做任何特殊的事情。所有原始类型(例如 int char bool 甚至 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 as:

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

之后,一切都应该正常工作。


I'm relatively new to C++. In Java, it's easy for me to instantiate and use a hashmap. I'd like to know how to do it in a simple way in C++, since I saw many different implementations and none of them looked simple to me.

解决方案

Most compilers should define std::hash_map for you; in the coming C++0x standard, it will be part of the standard library as std::unordered_map. The STL Page on it is fairly standard. If you use Visual Studio, Microsoft has a page on it.

If you want to use your class as the value, not as the key, then you don't need to do anything special. All primitive types (things like int, char, bool and even char *) should "just work" as keys in a hash_map. However, for anything else you will have to define your own hashing and equality functions and then write "functors" that wrap them in a class.

Assuming your class is called MyClass and you have already defined:

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

You will need to define two functors to wrap those methods in objects.

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

And instantiate your hash_map/hash_set as:

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

Everything should work as expected after that.

这篇关于在C ++中简单的hashmap实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆