为什么这个向量迭代器不能递增?

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

问题描述

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

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)