Re: Do vector iterators remain valid after resize() if base pointer
of elements remains unchanged?
On Mar 24, 3:43 pm, "Fred Zwarts" <F.Zwa...@KVI.nl> wrote:
"zr" <zvir...@gmail.com> wrote in
messagenews:1e21430a-6060-4167-a61a-df2248f8a83b@o36g2000yqh.googlegroups=
..com...
On Mar 24, 12:56 pm, zr <zvir...@gmail.com> wrote:
I hope the following example illustrates the question:
#include <vector>
int _tmain(int argc, _TCHAR* argv[])
{
float resize_factor = 1.3;
std::vector<int> sorted_image_id;
//..
int* base = &sorted_image_id.front();
sorted_image_id.resize(sorted_image_id.size()*resize_factor);
// optimization: reuse iterators after resize
if (&sorted_image_id.front() == base)
{
//Is it safe to assume all iterators are still valid?
} else
{
//Need to reassign iterators
}
//...
return 0;
}
I am not sure.
Could sorted_image_id.end() depend on the size of the vector
even if no reallocation occurs?
Or course it could.
If so, an iterator with this value before the resize may have
a value after the resize with at least a questionable value.
I think it's evident that he can only be talking about valid,
dereferenceable iterators. His code should work, but IMHO, it
doesn't look very idiomatic, and would raise questions in a code
review. I think something like:
bool iteratorsValid = array.capacity() >= newSize ;
array.resize( newSize ) ;
if ( iteratorsValid ) // ...
would be more typical and easier to understand.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34