久久久久久久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 表達式中的變量聲明)
主站蜘蛛池模板: 国产精品美女久久久久久久网站 | 亚洲精品二三区 | 九色 在线| 免费午夜电影 | 久久1区| 午夜免费观看 | 中文字幕乱码视频32 | 国产精品国产a | 久久国产精品一区二区 | 亚洲欧美综合精品久久成人 | 欧美日韩一区不卡 | 国产一区二区中文字幕 | 国产激情视频网站 | 日本精品一区二区三区在线观看视频 | 91看片网| 国产亚洲一区二区精品 | 日韩一级在线 | 亚洲欧美国产精品一区二区 | 日韩欧美在线观看视频网站 | 黄色一级特级片 | 日韩在线中文字幕 | av中文字幕在线 | 国产精品久久久久久妇女 | 美女131mm久久爽爽免费 | 国产精品久久久av | 国产精品精品视频一区二区三区 | 在线只有精品 | 亚洲一区 中文字幕 | 成人欧美一区二区三区在线观看 | 九九导航 | 在线看亚洲 | 男女下面一进一出网站 | 亚洲欧美激情国产综合久久久 | 欧美区在线观看 | 国产精品日韩在线观看一区二区 | 一级黄色av电影 | 一区二区三区av | 成人免费网站视频 | 四虎成人在线播放 | 欧美不卡网站 | 成人精品一区二区三区中文字幕 |