multimap vs map with set

时光总嘲笑我的痴心妄想 提交于 2019-11-30 11:35:05

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 the std::set. A multimap 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 or multimap with a string 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.

The "set" option will eliminate the key+value pairs duplications, whether the multimap won't.

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".

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< String, int > is most likely more memory efficient.

They are actually not equivalent anyway. A multimap<X,Y> allows storing duplicate key-value pairs, whereas a map<T, set<X>> does not.

multimap<int, int> m;
m.insert(make_pair(2, 3));
m.insert(make_pair(2, 3)); // This changes the size of m!

Whereas

map<int, set<int>> m;
m[2].insert(3);
m[2].insert(3); // This does nothing.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!