简体   繁体   English

删除问题并将元素添加到std :: vector的问题

[英]Problems erasing and adding elements to std::vector

I'm having some troubles adding and removing elements from an std::vector ( population , in the example code). 我在从std :: vector(示例代码中的population添加和删​​除元素时遇到了一些麻烦。 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. ***对象0x7f86a1404498的错误:释放的对象的校验和不正确-释放后可能已修改了对象。

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: 我想我以错误的方式使用了一些std :: vector属性,因为如果人口不是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? 你能帮助我吗?

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(); 您似乎已经意识到长度已更改,因为您将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. 修改后,您不能假定end有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM