简体   繁体   English

在std :: map中使用2个键

[英]Use 2 keys in std::map

I was trying to create a std::map with 2 keys. 我试图用2个键创建一个std::map I can do it with std::pair or create a struct and use it as the key. 我可以使用std::pair来完成它,或者创建一个结构并将其用作键。

In my software, there's a search function that is being called a lot. 在我的软件中,有很多搜索功能。 This function searches by the 1st or the 2nd key. 该功能通过第一或第二键进行搜索。

If I had about 1000 items in the map, I'm guessing it will take some time if I wanted to search it. 如果我在地图上有大约1000个项目,我想如果要搜索它会花费一些时间。 So I thought that if I make another std::map that holds the 2nd key and the value is 1st key, then I can take the value and search in the other map to get the real value. 所以我认为,如果我制作另一个保存第二个键的std::map ,并且值是1st键,那么我可以取该值并在另一个图中搜索以获得真实值。

But my guess is that this will take more memory. 但是我的猜测是,这将占用更多的内存。 What is the best option in this scenario? 在这种情况下最好的选择是什么?

Brute force approach 蛮力法

You can store your items in std::vector and have two maps: the first with your first key and pointers (or indices) to vector items and the second with your second key and pointers (or indices) to vector items. 您可以将项目存储在std::vector并具有两个映射:第一个具有第一个键和指向矢量项的指针(或索引),第二个具有第二个键和指向矢量项的指针(或索引)。 The problem is to maintain all three containers when your set is modified. 问题是修改集时要维护所有三个容器。

Pointers vs. indices: Pointers are dangerous as pointed correctly in the comment, but simpler if you're going to delete items from the vector. 指针与索引:指针在注释中正确指出是危险的,但是如果要从向量中删除项目,则指针更简单。 Otherwise indices are safer. 否则索引会更安全。

Smart approach 聪明的方法

You can use Boost.MultiIndex container that was designed for cases exactly like yours. 您可以使用专门为您的情况设计的Boost.MultiIndex容器。

This is an engineering decision that you'll have to resolve. 这是您必须解决的工程决策。

Multiple maps only makes sense (IMHO) if you know that the sets of key1 and key2 keys conflict. 如果您知道key1和key2键集冲突,则多个映射才有意义(IMHO)。 Otherwise, why not just insert both keys into the same map, each corresponding value referring to your object? 否则,为什么不只将两个键插入同一映射,每个对应的值都引用您的对象?

You don't want to duplicate your object, so you might put them in a vector, and put the vector index as the mapped value. 您不想复制对象,因此可以将它们放入向量中,并将向量索引作为映射值。 Or use a map of key-to-pointer, etc. 或使用键到指针的映射等。

1k items is not really that many, so I'm not concerned about the memory use here, but using a map instead of an unordered_map might be a concern (rb-tree vs. hash table). 1k项实际上并不多,因此这里我不关心内存的使用,但是可能要考虑使用映射而不是unordered_map(rb树与哈希表)。

Also, if you remove items from the map, you'll need to be able to remove both keys together, so be sure to account for that. 另外,如果您从地图上删除项目,则需要同时删除两个键,因此请务必考虑到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM