Jump to content

[SOLVED] Vector foreach iterator


photo

Recommended Posts

Hello

 

Problem:

Iterating through a vector with foreach leads to errors if an element is deleted.

Code:

foreach(SoundSource snd; ambientSoundActive)
{
   ambientSoundActive.remove(ambientSoundActive.find(snd));
}

Debug:

UserArray::forEachStep(): bad vector iteratorCall stack:
00: 0x0000a6c6 World::AmbientSoundManager::changedCondition()
01: 0x0000aabe World::Weather::WeatherManager::setWeather()
Disassemble:
0x0000a76d: forestep   snd in ambientSoundActive 0x0000a748
0x0000a771: foreinit   snd in toRemove 0x0000a781
Nice to have solution:
Iterator gets auto updated with new size and does not throw an error.

 

C++ Solution:

for (vector<int>::iterator it = res.begin(); it != res.end(); it++)
{
    res.erase(it--);
}
Link to comment
×
×
  • Create New...