Generally speaking is it a good idea to cache an end iterator (specifically STL containers) for efficiency and speed purposes? such as in the following bit of code:
Generally speaking is it a good idea to cache an end iterator (specifically STL containers) for efficiency and speed purposes?
If you use the STL container algorithms the caching of the end iterator is happens anyway (as you pass the result of container.end() as a parameter).
If you modify the memory of the container (insert/remove elements) it's a bad bad idea.
Also, caching for efficiency rarely makes much sense: in most cases the end() is inlined by the compiler, and when it is not, it is very probable that your efficiency doesn't hang on the end() result being cached. YMMV though.
I often use this style for iterating containers:
// typedef std::vector<Person> Persons;
Persons::iterator it = persons.begin(), end = persons.end();
for (; it != end; ++it)
{
Person & person = *it;
// ...
}
Erasing an element from a vector invalidates all iterators after the erased position.
I'm not certain about the other container types. In any case I think it would be safe to assume that all iterators become invalid after an erase. If you really need very specific information then you can always look it up. I rarely need this because because of my rather conservative coding style.