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

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

问题描述

我正在尝试删除向量的内容,但出现错误 - 向量迭代器不可递增,这是为什么呢?

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天全站免登陆