从向量中删除项目,而在 C++11 范围“for"循环中?

2021-12-11 00:00:00 for-loop vector c++ c++11

我有一个 IInventory* 向量,我正在使用 C++11 范围遍历列表,以对每个列表进行处理.

I have a vector of IInventory*, and I am looping through the list using C++11 range for, to do stuff with each one.

在对一个对象进行一些操作后,我可能想将其从列表中删除并删除该对象.我知道我可以随时在指针上调用 delete 来清理它,但是在 for 循环范围内从向量中删除它的正确方法是什么?如果我从列表中删除它,我的循环会失效吗?

After doing some stuff with one, I may want to remove it from the list and delete the object. I know I can call delete on the pointer any time to clean it up, but what is the proper way to remove it from the vector, while in the range for loop? And if I remove it from the list will my loop be invalidated?

std::vector<IInventory*> inv;
inv.push_back(new Foo());
inv.push_back(new Bar());

for (IInventory* index : inv)
{
    // Do some stuff
    // OK, I decided I need to remove this object from 'inv'...
}

推荐答案

不,你不能.基于范围的 for 适用于需要访问容器的每个元素一次的情况.

No, you can't. Range-based for is for when you need to access each element of a container once.

如果您需要在进行过程中修改容器、多次访问元素或以其他方式以非线性方式迭代,则应使用普通的 for 循环或其同类循环之一通过容器.

You should use the normal for loop or one of its cousins if you need to modify the container as you go along, access an element more than once, or otherwise iterate in a non-linear fashion through the container.

例如:

auto i = std::begin(inv);

while (i != std::end(inv)) {
    // Do some stuff
    if (blah)
        i = inv.erase(i);
    else
        ++i;
}

相关文章