A vector or multimap dilemma
I have a dilemma of whether to have a multimap <int key, int value>
or maintain a vector containing a vector of all values corresponding to int key.
I'm interested in which performs faster when looking up the values f开发者_高级运维or a certain int key.
If you want a multimap
and not just a map
, the alternative will probably be a vector< list<int> >
or something like that (a multimap
, being generally implemented as an RB tree that allows multiple equivalent keys, is somewhat akin to a map
with a list
element type).
In general, a vector
lookup is faster: it's O(1)
for the array vs O(log n)
for the map (in both case I'm not counting the search into the list
/vector
/set
/whatever is used for the "multi" part). But, to use the vector
, you have to make it as big as the biggest int
key you want to use; if your keys are sequential this is not a problem, but if your index is sparse the multimap
can be a better choice.
On the other hand, if you don't need ordered traversal, unordered_multimap
(which is actually a hash table) could be the best of both worlds: you get array-like O(1)
lookup without having to keep an enormous empty array.
Forget which is "faster". You can profile it later, but don't obsess over this. Far more important is that one approach gives you sparse storage, and the other does not -- focus on this and decide which is the most appropriate for your problem.
I would say if your keys are sequential go with the vector, but if there are big holes in your keys then the map will be better (as you won't have to store "empty" records as in your vector), plus it will make it easier to count how many records you have etc. Performance wise vectors are based on arrays so lookups are generally faster (as maps have to go through a few pieces of data to do a lookup).
I would recommend map<int, vector<int>>
Since once you have done the search in the map you have a vector with all the values.
Otherwise you solution will require a new search of each value
I guess you are doing premature optimization. It's not good because you should optimize only after everything is working with use of profilers. Don't waste time and use a specialized container for your needs.
精彩评论