向 std::vector 擦除和添加元素时出现问题

Problems erasing and adding elements to std::vector

我在从 std::vector(population,在示例代码中)中添加和删除元素时遇到了一些问题。我想要做的是在满足条件时擦除元素,而在满足其他条件时复制元素。这是代码:

    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();

我得到的是:

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

我猜我用错了一些 std::vector 属性,因为如果 population 是 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();

你能帮帮我吗?

您发布的代码还不够多。

我假设你在片段的开头省略了:

walkers_num = population.size();

并且正在尝试访问整个数组。在那种情况下尝试:

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.
        }
    //....

你好像意识到长度变了,因为你把walkers_num = population.size();放在了最后。您需要全程跟踪。

您的迭代器代码可能有效但在技术上同样无效的原因有一些微妙的原因。您不能假设 end 修改后有效。