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

2022-01-10 00:00:00 memory-management iterator vector c++

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

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

相关文章