久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

從向量中刪除項目,而在 C++11 范圍“for"循環(huán)

Removing item from vector, while in C++11 range #39;for#39; loop?(從向量中刪除項目,而在 C++11 范圍“for循環(huán)中?)
本文介紹了從向量中刪除項目,而在 C++11 范圍“for"循環(huán)中?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我有一個 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模板網!

【網站聲明】本站部分內容來源于互聯(lián)網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯(lián)系我們刪除處理,感謝您的支持!

相關文檔推薦

What do compilers do with compile-time branching?(編譯器如何處理編譯時分支?)
Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 嗎?)
Checking for NULL pointer in C/C++(在 C/C++ 中檢查空指針)
Math-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比較運算符的數(shù)學式鏈接-如“if((5<j<=1)))
Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之間的區(qū)別與“if())
C++, variable declaration in #39;if#39; expression(C++,if 表達式中的變量聲明)
主站蜘蛛池模板: 亚洲欧美一区二区三区视频 | 久久手机在线视频 | 日本福利片| 91精品一区二区 | 一区二区av | 毛片高清 | 日韩欧美一区二区三区 | 日韩欧美三区 | 久久成人国产精品 | 超碰在线网站 | 中国一级大黄大片 | 日日操日日干 | 免费一级做a爰片久久毛片潮喷 | 午夜成人在线视频 | 国产精品无码久久久久 | 国产999精品久久久影片官网 | 91原创视频| 中文字幕国产视频 | 香蕉91| 国产精品视频网站 | 欧美一级免费看 | 亚洲一区二区三区在线免费观看 | 欧美一级片久久 | 亚洲高清一区二区三区 | 亚洲精品一区二三区不卡 | 国产精品一区二区欧美 | 久久人人网 | 国产精品久久久久久婷婷天堂 | 欧美一区在线视频 | 亚洲国产精品一区二区第一页 | 国产精品视频免费看 | 国产精品久久久久久久久婷婷 | 久久精品久久久久久 | 成人精品久久久 | 国产97视频在线观看 | 久久艹免费视频 | 九九热在线免费观看 | 成人国产精品久久久 | 青娱乐一区二区 | 黄色大片免费观看 | 亚洲精品久久久9婷婷中文字幕 |