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

时间:2023-01-20
本文介绍了从向量中删除项目,而在 C++11 范围“for"循环中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个 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;
}

这篇关于从向量中删除项目,而在 C++11 范围“for"循环中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:我可以使用 break 退出多个嵌套的“for"循环吗? 下一篇:每次循环迭代相同的随机数

相关文章

最新文章