Caching the end iterator - Good idea or Bad Idea?

If we are talking about efficiency and speed: caching the end iterator is unnecessary because of compiler optimizations and inlining.


In the simple case of a vector, the end iterator will change when you add or remove elements from the container; though, it's usually safest to assume that if you mutate the container while iterating over it, all iterators to it become invalid. Iterators may be implemented differently in any given STL implementation.

With regard to caching the end iterator -- it's certainly valid to cache it, but to find out if it is actually faster in your case, the best bet is for you to profile your code and see. While retrieving the end iterator from a vector is likely a fast implementation with a recent STL library and compiler, I have worked on past projects where caching the end iterator gave us a significant speed boost. (This was on the PlayStation 2, so do take with a grain of salt.)


Erasing from a container over which you are currently iterating is always a bad idea. The actual caching of your end iterator is not going to change that.

h.