
Eric Niebler schrieb:
Incidently, if it is caching then code like:
BOOST_FOREACH( int i, vec ) if (condition(i)) vec.push_back( filter(i) );
will not work the same as:
vec.reserve(a lot);
for (iterator i = vec.begin(); i != vec.end(); ++i) if (condition(*i)) vec.push_back( filter(*i) );
Neither of these loops "work" -- they are both broken in the same way. They both invalidate the iterator they are using.
[5] A vector's iterators are invalidated when its memory is reallocated. Additionally, inserting or deleting an element in the middle of a vector invalidates all iterators that point to elements following the insertion or deletion point. It follows that you can prevent a vector's iterators from being invalidated if you use reserve() to preallocate as much memory as the vector will ever use, and if all insertions and deletions are at the vector's end. i is never following the insertion point. -- Stefan Strasser