问题描述
我对 C++ 比较陌生.在 Java 中,我很容易实例化和使用 hashmap.我想知道如何在 C++ 中以简单的方式实现它,因为我看到了许多不同的实现,但对我来说它们都不简单.
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.
推荐答案
大多数编译器应该为你定义std::hash_map;在即将到来的 C++0x 标准中,它将成为标准库的一部分,如 std::unordered_map.STL Page 是相当标准的.如果您使用 Visual Studio,Microsoft 有一个页面就可以了.
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.
如果你想使用你的类作为值,而不是作为键,那么你不需要做任何特别的事情.所有原始类型(像 int、char、bool 甚至 char * 之类的东西)都应该正常工作"hash_map 中的键.但是,对于其他任何事情,您都必须定义自己的散列和相等函数,然后编写将它们包装在一个类中的函子".
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.
假设你的类被称为 MyClass 并且你已经定义了:
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);
}
};
并将您的 hash_map/hash_set 实例化为:
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 ++中的简单哈希图实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)