Simple hashmap implementation in C++(C ++中的简单哈希图实现)
问题描述
我对 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 ++中的简单哈希图实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C ++中的简单哈希图实现
基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
