开发者

multimap vs map with set

开发者 https://www.devze.com 2023-04-03 09:12 出处:网络
I\'m wondering which is more efficient. std::map< String, std::set<int> > or std::multimap< String, int >

I'm wondering which is more efficient.

std::map< String, std::set<int> >

or

std::multimap< String, int >

EDIT: I do not plan on doing anything out of the ordinary with these maps. Standard insert, delete, 开发者_JAVA百科modify, search. The size of each set or multi keyed String shouldn't be more than 100.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消