問題描述
我有一個 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
循環(huán)范圍內從向量中刪除它的正確方法是什么?如果我從列表中刪除它,我的循環(huán)會失效嗎?
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
循環(huán)或其同類循環(huán)之一通過容器.
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"循環(huán)中?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!