tags:

views:

65

answers:

2

Hi all

do you know if it is any difference in performance when I access a std::map element using find or operator []? One returns an iterator and the other a const ref to the object. Which one might be quicker becuase of all of the behind the scene of the STL?

Regards AFG

+3  A: 

When you use [] on a key that doesn't exist, the default element will be inserted. This default element depends on your map definition (for example, for an int it will be a zero).

When you use find, there is no "automatic" insertion, so it can be quite faster if you often search for keys that does not exist.

Guillaume Lebourgeois
I would add that operator[] basically call find. If the element does not exist, it uses the position where the element should have been to add it. It "just" cost en element construction.
Scharron
Good point. Just comparing speed between two things that doesn't do the same thing tend to be misleading.
Mattias Nilsson
A: 

find() is O(n). operator [] is O(1). Therefore the latter is (usually) faster.

Ignacio Vazquez-Abrams
It depends on your map implementation.Requirements for std::map is O(log(n)) for find (and operator [] uses more or less find).
Scharron
You must be confused between hashmaps and maps.
Guillaume Lebourgeois