从向量中删除项目,而在 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"循环中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)