在C ++ 11范围for for循环中移除vector中的项目? [英] Removing item from vector, while in C++11 range 'for' loop?

查看:150
本文介绍了在C ++ 11范围for for循环中移除vector中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个IInventory *的向量,我正在循环使用C ++ 11范围的列表,每个都做一些事情。

一些东西,我可能想要从列表中删除它,并删除对象。我知道我可以在指针上随时调用 delete 来清理它,但是在<$ c $范围内,从vector中移除它的正确方法是什么c> for 循环?如果我从列表中删除它,我的循环将被无效?

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

(IInventory * index:inv)
{
//做一些东西
//确定,我决定我需要从'inv' ...


解决方案

不能。基于范围的 for 适用于您需要访问容器的每个元素一次。



您应该使用正常 for 循环或其一个表兄弟,如果你需要随时修改容器,不止一次访问一个元素,或者以非线性方式迭代

例如:

  auto i = std: :(INV)开始; (i!= std :: end(inv)){
//做一些事情
if(blah)
i = inv.erase(i) ;
else
++ i;
}


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

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'...
}

解决方案

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

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.

For example:

auto i = std::begin(inv);

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

这篇关于在C ++ 11范围for for循环中移除vector中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆