views:

2053

answers:

5

What is the performance difference between using an iterator to loop through an STL map, versus a vector? I'd like to use the map key for insertion, deletion, and some accesses, but I also need to do regular accesses to every element in the map.

+1  A: 

Use map if you need fast way of access by the key. Otherwise use vector all the time unless some performance issues will be discovered with profiler.

Mykola Golubyev
Access of every element in the map is somewhat more important, as it's going to be firing off frequently, but I still need reasonably quick key-based lookup (I can take out that requirement, but things will get unreasonably hairy). Map does seem to be the better fit, per Greg Rogers' answer above.
+1  A: 

Iterating through every element of a map takes O(n) time. wikipedia

Sanjaya R
I don't know why someone downvoted. It is truly O(N) for transversing the whole tree.
David Rodríguez - dribeas
I'd be nice if it'd show who down voted.
Sanjaya R
To make a bloody revenge? :)
topright
Upvoted for the justice.
topright
+2  A: 

Browsing the tree is not expensive (grosso modo like following a linked list), you won't benefit from the cache as much with a vector, but generally it's what you do when you iterate that is expensive, not the iteration itself.

Could you tell us more about what you expect to do when you iterate through the whole map?

Edouard A.
+4  A: 

With both map and vector, iterating through the entire collection is O(N). however (like list vs vector) vector stores elements contiguously, so accessing the next element is much cheaper because it will use cache optimally, whereas the map won't.

But since you need to have lookup based on keys, there isn't really an alternative. You could use a vector of pairs sorted on the first element, but if the collection needs to be mutable this is going to be very slow. Just use a map.

Greg Rogers
+1  A: 

This link has a nice table of performance for various operations on all of the STL containers.

Generally speaking, if you need to do a lot of inserting, removing or searching based on a key then the map is the way to go.

If you only need to set up the container once and then access it like an array then use a vector.

17 of 26
There is a subtlety in the question. The user does not want to access one element, but rather _all_ elements in the map. Amortized cost analysis yields O(N) for the whole map transversal (each edge in the tree is transversed only twice, once downwards, once upwards).
David Rodríguez - dribeas
The link is broken. I guess it should be: http://devmentor.org/references/stl/stl.php
Steph