多重贴图与带集合的贴图
我想知道哪个更有效率。
std::map< String, std::set<int> >
或
std::multimap< String, int >
编辑: 我不打算对这些地图做任何不寻常的事情。标准插入、删除、修改、搜索。每个集合或多键字符串的大小不应超过 100。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我认为这取决于实现,但这是一个(未)受过教育的猜测:
实际上,它取决于您将在
multimap
或std::set
中保留的整数数量代码>.在对键进行 log(n) 搜索之后,multimap
很可能会使用线性搜索值。如果您有大量整数值,则对键进行 log(n) 搜索,然后对值进行 log(n) 搜索可能会稍快一些。然而,就效率而言,使用
string
键将任何内容存储在map
或multimap
中几乎肯定会超过这两种情况的差异。如下所述,
multimap
可能会更易于使用且更易于维护,从而具有明显的优势。This I believe is implementation dependant, but an (un)educated guess:
In practice it depends on the number of integers that you will be keeping in the
multimap
or thestd::set
. Amultimap
will most likely use a linear search of the values after the log(n) search of the key. If you have a large number of integer values, then the log(n) search of the keys followed by a log(n) search of the values may be slightly faster.However, in terms of efficiency, storing anything in a
map
ormultimap
with astring
key will almost certainly outweigh the differences in either case.As said below, a
multimap
will likely be easier to use and more clear to maintain giving it a distinct advantage.“set”选项将消除键+值对的重复,无论多重映射是否不会。
The "set" option will eliminate the key+value pairs duplications, whether the multimap won't.
无论如何,它们实际上并不等同。
multimap
允许存储重复的键值对,而map>
则不允许。否则
因此,除非您需要重复的键值对, 我会使用 set 方法。语法也更好。我预计性能和内存使用方面的差异不会那么大。
They are actually not equivalent anyway. A
multimap<X,Y>
allows storing duplicate key-value pairs, whereas amap<T, set<X>>
does not.Whereas
So I would use the set approach unless you need duplicate key-value pairs. The syntax is also nicer. I expect the difference in performance and memory use is not that great.
如果您到目前为止对这些答案不满意(并不是说您不满意)并且我绝对被迫回答,我也会给出我有根据的“猜测”:
要插入,多重映射似乎更“有效” 。使用映射方法,您首先必须检索集合,然后对集合执行操作。
要删除/检索,地图似乎更“高效”。
If you're not happy with those answers so far (not saying that you are not) and I am absolutely forced to answer, I'll give my educated "guess" too:
To insert, the multimap appears to be more "efficient". With the map approach, you first have to retrieve, then perform operation on the set.
To delete/retrieve, map seems more "efficient".
我不能肯定地说,但考虑到 multimap 的设计目的是执行另一个表达式的操作,最好具体化并使用 multimap,它更有意义,它还具有用于使用的成员函数多重映射作为一个概念,使用其他方法这些函数会有点时髦。
I can't say for sure but given that multimap was designed to do what the other is an expression of, it should be better to be specific and use the multimap, it makes a lot more sense, it also has member functions for working with a multimap as a concept, those functions would be a bit funky using the other approach.
std::multimap<字符串、整数>很可能更有效率的内存。
std::multimap< String, int > is most likely more memory efficient.