PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

STL Vector reallocation during iteration

I'm using the STL <vector> in a program and I've run into a problem...

Basically, I've got a vector of a structure, and I iterate through and sometimes want to 'spawn' a new structure during the iteration.

simplistic code:
Code:


void LoopAll
{
std::vector<EnemyInfoStruct>::iterator pos;

for(pos = Lenemies.begin(); pos != Lenemies.end(); ++pos)
{
//do some stuff
//call a function which _MAY_ call ...
AddOne();

}
}

void AddOne()
{
EnemyInfoStruct * pp;

pp = Lenemies.insert(Lenemies.end());
// ... initialize
}



I know that reallocation _MAY_ occur if you add or delete items from the vector - and that I can use Lenemies.reserve(500) or something to keep it from happening... A reallocation make the interator 'pos' invalid and crashes the program (I think).

But what if I don't want to specify a max? The only solution I've come up with is to have another <vector> that I add items to during the iteration, and then once it's over, copy them into the desired <vector>.

Anyone have an opinion on this? The only things I've found so far is just "don't do that" and not what to do instead.

Thanks.
Why not use a std::list<> then? Or you could use an index instead of an iterator:

for (size_t i = 0; i != vector.size(); ++i)
{
...
}
Reallocation and iterator invalidation are two different things. You can have iterator invalidation even without a reallocation. The standard specifies when these can and cannot occur.

If you reserve enough space to prevent reallocations, and always add/delete at the end of the vector, it will be fine.

You need to take a look at your requirements, know the standard library, and choose the container that best satisfies the tradeoffs involved.

Using integer indices might be a simple way to get what you want.