vector :: erase()无法正常工作 [英] vector::erase() not working as expected

查看:360
本文介绍了vector :: erase()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在上面的代码片段中,我删除了已经存在的数字的倍数原始矢量2到9999(Eratosthenes筛)。我只有什么数字,超过1000,但不知何故这些都没有被删除。

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?

提前感谢。

推荐答案

调用 erase()你应该使用返回值,它是被删除的元素之后的值的迭代器,例如

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

但是,如果您进行此更改(必须!),您需要删除 ++ it2 。您还需要对 it1 进行两个更改。这是一些未经测试的代码:

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;
}

请注意,擦除 it2 之前 之前 c>因为 it2 = it1 + 1 。所以你不需要关心这种干扰。

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.

这篇关于vector :: erase()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆