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

Removing item from vector, while in C++11 range #39;for#39; loop?(从向量中删除项目,而在 C++11 范围“for循环中?)
本文介绍了从向量中删除项目,而在 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"循环中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

相关文档推荐

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?(易失性成员变量与易失性对象?)