vector::erase() not working as expected

人盡茶涼 提交于 2019-12-04 04:35:10

问题


  for(it1=prime.begin();it1<prime.end();it1++){
        for(it2=it1+1;it2<prime.end();it2++){

            if(*it2%*it1==0){

                prime.erase(it2);
            }

        }
        if(*it1<1000)
        prime.erase(it1);
    }

In above code snippet i am removing numbers that are multiples of number already existing in prime vector 2 to 9999(sieve of Eratosthenes).also I only what numbers that are more then 1000, but somehow these are not getting erased.

can someone please explain me why?

Thanks in advance.


回答1:


Calling erase() invalidates the iterator. You should use the return value, which is an iterator to the value after the element that was deleted, e.g.

it2 = prime.erase(it2);

But if you make this change (which you must!), you need to remove ++it2 from the for loop. You also need to make both changes for it1. Here is some untested code:

for (it1 = prime.begin(); it1 < prime.end();) {
    for(it2 = it1 + 1; it2 < prime.end();) {
        if (*it2 % *it1 == 0)
            it2 = prime.erase(it2);
        else
            ++it2;
    }
    if (*it1 < 1000)
        it1 = prime.erase(it1);
    else
        ++it1;
}

Note that erasing it2 will not invalidate it1, because it occurs strictly before it2 due to the it2 = it1 + 1. So you don't need to concern yourself with that interference.




回答2:


If you want to erase item and loop, you need do 'it1=prime.begin();' again after erasing. Because of the arrangement.



来源:https://stackoverflow.com/questions/4531330/vectorerase-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!