C ++中的简单哈希图实现

Simple hashmap implementation in C++(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.

如果你想使用你的类作为值,而不是作为键,那么你不需要做任何特别的事情.所有原始类型(像 intcharbool 甚至 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 ++中的简单哈希图实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)