问题描述
我有一个 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"循环中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)