从向量中删除项目,而在c ++ 11范围for循环? [英] Removing item from vector, while in c++11 range for loop?

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

问题描述

我有一个IInventory *的向量。
我使用c ++ 11范围循环遍历列表,每个都做一些东西。
在使用一些东西后,我可能想从列表中删除它,并删除对象。
我知道我可以调用delete的指针任何时候清理它,但什么是正确的方法将其从向量中删除,而在范围for循环?如果我从列表中删除它,我的循环会失效吗?

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

for(IInventory * index:inv)
{
//做一些东西
//确定我需要从inv中删除此对象?
}


解决方案



您应该使用如果你需要随时修改容器,多次访问一个元素,或者以非线性方式迭代,通过 c> c>



例如:

  auto i = std: :begin(inv); 

while(i!= std :: end(inv)){
//做一些东西
if(blah)
i = inv.erase ;
else
++ i;
}


I have a vector of IInventory* . 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 it's 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循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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