以两个值作为键的哈希表

Hashtable with both values as key

是否有基于散列的数据结构,我可以在 O(1) 时间内根据键和值搜索项目。

这可以通过颠倒键和值在列表中为每个键值 par 添加重复条目来实现,但这需要双倍的 space。

这种数据结构在某些情况下可能会有用:比如我想在映射中存储左括号和右括号,在解析字符串时,如果键存在,我可以只检查映射而不用担心是开闭图还是闭开图还是不存副本

希望我说得够清楚!!

满足您需求的数据结构称为双向映射。

我想你是在寻找现有的实现,而不是寻找如何实现它的指针 :) 因为你没有指定编程语言,这就是 Java 的当前情况 - 有Java API 中没有这样的数据结构。但是,Google Guava 的 bi-directional map 接口有多种实现。来自文档:

A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.

或者,BidiMap 来自 Apache Collections。

对于 C++,请查看 Boost.Bimap

对于Python,看看bidict

在 C# 以及其他语言中,不存在官方实现,但这就是 Jon Skeet comes in

您正在搜索 bidirectional map. Here 是一篇描述 C++ 实现的文章。请注意,双向地图基本上是将两个地图合并为一个对象。没有比这更有效的解决方案了,原因很简单:

a map is basically an unconnected directed graph of (key,value)-pairs. Each pair is represented by an edge. If you want the map to be bidirectional you'll wind up with twice as many edges, thus doubling the amount of required memory.

C++ 和 Java STL 不为此目的提供任何 类。在 Java 中,您可以使用 Google 的 Guava 库,在 C++ 中,boost-library 提供双向映射。