Problems erasing and adding elements to std::vector

118 views Asked by At

I'm having some troubles adding and removing elements from an std::vector (population, in the example code). What I want to do is to erase an element if a condition is satisfied and copy the element if instead other conditions are satisfied. Here's the code:

    for( int i = 0; i < walkers_num;  i++) {

        if( population[i].molteplicity == 0 ) { 
            population[i] = population.back();
            population.pop_back();
            i--;

        } else {

            for( int j = population[i].molteplicity; j > 1; j-- ) { 
                population.push_back(population[i]); 
            }
        }
    }
    walkers_num = population.size();

What I get is:

*** error for object 0x7f86a1404498: incorrect checksum for freed object - object was probably modified after being freed.

I guess I'm using some std::vector property in a wrong way, since a very similar algorithm (conceptually they seem identical to me) seems to work if population is instead an std::list:

list<Walker>::iterator it;
list<Walker>::iterator end = thread_population[i].end();

for ( it = thread_population[i].begin(); it != end; ) {
if( it->molteplicity == 0 ) { 
        it = thread_population[i].erase(it); 
        continue;
    }

    for( int j = it->molteplicity; j > 1; j-- ) { 
        population.push_back(*it); 
    }

    ++it;
}
walkers_num = population.size();

Can you help me?

1

There are 1 answers

1
Persixty On BEST ANSWER

You haven't posted quite enough code.

I'm assuming you omitted at the start of the fragment:

walkers_num = population.size();

And are trying to visit the whole array. In that case try:

walkers_num = population.size();
for( int i = 0; i < walkers_num;  i++) {
        if( population[i].molteplicity == 0 ) { 
            population[i] = population.back();
            population.pop_back();
            i--; 
            --walkers_num; //Array has been shortened.
        }
    //....

You seem to have realised the length has changed because you put walkers_num = population.size(); at the end. You need to keep track throughout.

There are subtle reasons why your iterator code is likely to work but technically just as invalid. You're not allowed to assume end is valid after a modification.