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:
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.
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.