向量迭代器擦除给我一个运行时错误? [英] Vector iterator erase giving me a runtime error?

查看:22
本文介绍了向量迭代器擦除给我一个运行时错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在我的班级里有一个方法,这个班级应该做的是,检查我在 .h 文件中的向量是否有 double low & 之间的值.double high 然后删除它们,最后返回删除了多少个空格"

So I got a methode inside my class, and what this class is supposed to do is, check if the vector i have in the .h file have values bewtween double low & double high and then delete those and at last return how many "spaces" got removed

所以我尝试了一些东西,但我总是遇到运行时错误,它似乎在 for 循环中,但我不知道为什么.

So I tried a few things and i always get runtime errors, it seems to be in the for loop, but i can´t figure out why.

这是我试过的,

首先,我试着按照我认为可行的方式去做:

First I tried to just do it the way I felt like it would work:

int datastorage::eraseDataPointsBetween(double low,double high) 
{
    int antal = 0;
    for (vector<double>::iterator i = data_.begin(); i !=data_.end();i++)
    {
        if (*i >=low && *i <=high)
        {
            data_.erase(i);
            antal++;
        }

    }
    return antal;
}

但后来我尝试进行一些调试,我可以看到它实际上没有意义,因为当某些东西被删除时它仍然会增加(所以如果我们删除space 2"它实际上会检查下次空格 4(因为擦除后第 3 点变成了第 2 点)))

But then I tried to do some debugging and I could see that it actually doesn´t make sence to have it like that as when something gets deleted it still gets incremented(so if we delete "space 2" it would actually check space 4 next time(as spot 3 get to be spot 2 after erase)))

所以我试着把它改成这个

So I tried to change it to this

int datastorage::eraseDataPointsBetween(double low,double high) 
{
    int antal = 0;
    for (vector<double>::iterator i = data_.begin(); i !=data_.end();)
    {
        if (*i >=low && *i <=high)
        {
            data_.erase(i);
            antal++;
        }
        else 
            i++;
    }
    return antal;
}

每当我不删除空格时它只会增加 i(所以如果我删除space 2",它会在下次运行时检查新的space 2")

Where it only increment the i whenever i do not remove a space(so if I delete "space 2", it will check the new "space 2" next run)

这也给了我一个语法错误expression: vector iterators incompatible

This also gives me a syntax error expression: vector iterators incompatible

希望你能帮忙,因为我很迷茫

Hope you can help because I'm pretty lost

推荐答案

vector::erase 使迭代器失效,因此您无法在调用后使用它来擦除.您应该通过这种方式从 vector 中擦除:

vector::erase invalidates iterator so you cannot use it after call to erase. You should erase from a vector this way:

int datastorage::eraseDataPointsBetween( double low, double high)  {
  int antal = 0;
  for( vector<double>::iterator i = data_.begin(); i !=data_.end())
  {  
     if( (*i >= low) && (*i <= high))
     {
        i = data_.erase( i); // new (valid) iterator is returned
        ++antal;
     }
     else
     {
        ++i;
     }

   return antal;
}

这篇关于向量迭代器擦除给我一个运行时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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