如何实现具有多个键的快速地图?
我正在寻找可以执行多个键查找的 C++ 关联映射容器类型。地图需要有恒定的时间查找,但我不在乎它是有序的还是无序的。它只需要快。
例如,我想在地图中存储一堆 std::vector
对象,并使用 int
和 void*
作为查找键。 int
和 void*
都必须匹配才能检索我的向量。
这样的容器已经存在吗?或者我必须自己推出?如果是这样,我该如何实施?我一直在尝试将 boost::unordered_map
存储在另一个 boost::unordered_map
中,但我还没有使用此方法取得任何成功。如果没有更简单的方法的话,也许我会继续潘兴这个方法。
I'm looking for a C++ associative map container type which I can perform multiple key lookups on. The map needs to have constant time lookups, but I don't care if it's ordered or unordered. It just needs to be fast.
For example, I want to store a bunch of std::vector
objects in a map with an int
and a void*
as the lookup keys. Both the int
and the void*
must match for my vector to be retrieved.
Does such a container exist already? Or am I going to have to roll my own? If so, how could I implement it? I've been trying to store a boost::unordered_map
inside another boost::unordered_map
, but I have not had any success with this method, yet. Maybe I will continue Pershing this method if there is no simpler way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
持续查找需要哈希图。您可以使用 boost::unordered_map (或tr1)。关键是组合哈希 int 和 void 指针。
Constant look up requires a hash map. You can use a the boost::unordered_map (or tr1). The key would be the combined hash of the int and the void pointer.
如果你不想使用boost,你可以尝试
map< int,map>
。然而,查找的时间复杂度为 O(log(map size))。If you don't want to use boost, you can try
map< int, map<void*, vector> >
. The lookups are however O(log(map size)).自 C++11 起,您还可以使用
std::unordered_map
,因为它似乎非常适合您的要求:为了将
int
和void*
组合成一个键,您可以使用std::pair
。为了使无序映射与该对一起工作,您必须指定一个合适的哈希函数。为了使下面的示例简短,我使用 手工制作的 lambda 表达式。如果此函数导致性能问题,您可能需要创建更复杂的哈希。
您没有指定向量的内容,因此为了简单起见,我选择了
int
。但是,您可以使解决方案适应任何矢量内容。总而言之,您的代码可能如下所示:Code on Ideone
Since C++11 you can also use an
std::unordered_map
, as it seems to fit your requirements quite nicely:In order to combine your
int
andvoid*
into a single key, you can make use ofstd::pair
.To make the unordered map work with the pair, you have to specify a suitable hash function. In order to keep the following example short, I use a handcrafted combination of
std::hash<>
function calls inside a lambda expression. In case this function causes performance problems, you might want to create a more sophisticated hash.You didn't specify the content of your vectors, so I chose
int
for the sake of simplicity. However, you can adapt the solution to any vector content. All in all your code could look as follows:Code on Ideone
您可以使用 boost::multi_index。
(尽管我认为您真正想要的是使用包含 void* 和整数的类型作为映射的键,并且只是比较两者的原始数据以便为映射提供比较运算符)
You could use boost::multi_index.
(although I think what you actually want is to use a type that contains both the void* and the integer as the key to your map, and just to compare the raw data for both in order to provide the comparison operator for the map)