为什么这个向量迭代器不可增量? [英] Why is this vector iterator not incrementable?

查看:202
本文介绍了为什么这个向量迭代器不可增量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除向量的内容,我得到一个错误 - 向量迭代器不可递增,为什么?

I'm trying to delete the vector's content and I'm getting an error - vector iterator is not incrementable, why is that?

这是我的析构函数:

City::~City()
{
    vector <Base*>::iterator deleteIterator;
    for (deleteIterator = m_basesVector.begin() ; deleteIterator != m_basesVector.end() ; deleteIterator++)
        m_basesVector.erase(deleteIterator);
}  

感谢。

推荐答案

erase 使迭代器无效。你不能再使用它了。幸运的是,它返回一个迭代器,你可以使用:

erase invalidates the iterator. You can't use it any more. Luckily for you, it returns an iterator that you can use:

vector <Base*>::iterator deleteIterator = m_basesVector.begin();
while (deleteIterator != m_basesVector.end()) {
    deleteIterator = m_basesVector.erase(deleteIterator);
}

或:

m_basesVector.clear();

您是否负责释放向量中的指针引用的内存?如果这是你迭代的原因(和你的真正的程序有更多的代码,你没有显示,释放那些对象在循环),然后记住,从向量的开始删除是一个缓慢的操作,因为在每个步骤,向量的所有元素必须向下移动一个位置。更好的是循环遍历向量释放一切(然后 clear()向量,虽然像Mike说,如果向量是被销毁的对象的成员)。

Are you responsible for freeing the memory referred to by the pointers in the vector? If that's the reason that you're iterating (and your real program has more code that you haven't shown, that frees those objects in the loop), then bear in mind that erasing from the beginning of a vector is a slow operation, because at each step, all the elements of the vector have to be shifted down one place. Better would be to loop over the vector freeing everything (then clear() the vector, although as Mike says that's not necessary if the vector is a member of an object that's being destroyed).

这篇关于为什么这个向量迭代器不可增量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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