Alex Rivera | Logout

vector or map, which one to use?

Asked 2009-01-18T07:06:05.053
99

I've heard many people say that if the number of expected elements in the container is relatively small, it is better to use std::vector instead of std::map even if you were to use the container for lookups only and not iterating.

What is the real reason behind this?

Obviously the lookup performance of std::map cannot be worse than std::vector (although it may differ in nanoseconds/microseconds) so does it have something to do with memory usage?

Does std::vector fare any better/worse than std::map in fragmenting the virtual address space?

I am using the STL library that comes along with Visual Studio (i.e. Microsoft's implementation). Does that make any difference compared to other implementations?

Edit
Report

1 Answer

4

Another way to look at this, is if we're talking about small containers, then neither one is going to take very long to look up. Unless you're searching through this container on a very tight loop, the difference in time will probably be negligible.

In that case, I would look for which container more closely matches what you want to do. If you're looking for a particular value, map's built-in find() method will be a lot easier (and less complex to use) than creating a for loop and iterating over a vector.

Your own time is probably worth a lot more than a few nano-seconds here and there.

answered 2009-01-18T14:12:17.183

Your Answer