[英]How to remove from a list inside a for loop in c++
有沒有辦法刪除循環遍歷該列表的 for 循環中的列表項? 例子:
std::list<int> myList;
myList.push_back(5);
myList.push_back(8);
std::list<int>::iterator i;
for (i = myList.begin(); i != myList.end(); i++)
{
if (i == 8)
// myList.remove(*i);
}
有沒有辦法用其他東西替換myList.remove(*i)
,因為這會產生錯誤。
要擦除所有等於 8 的項目,只需使用擦除/刪除習語。 無需編寫任何循環:
#include <list>
#include <algorithm>
#include <iostream>
int main()
{
std::list<int> myList;
myList.push_back(5);
myList.push_back(8);
std::cout << "Before:\n";
for (auto i : myList)
std::cout << i << "\n";
// Erase all the items that equal 8
myList.erase(std::remove(myList.begin(), myList.end(), 8), myList.end());
std::cout << "\nAfter:\n";
for (auto i : myList)
std::cout << i << "\n";
}
輸出:
Before:
5
8
After:
5
您正在使用iterator
因此有一個方法erase 。 你可以像這樣使用
while (i != myList.end())
{
if (*i == 8) // dereferance the i
i = myList.erase(i);
else i++;
}
首先也是最重要的:如果迭代整個列表只是為了刪除所需的項目,只需使用list::remove
而不使用循環。 它會為你做的伎倆。
但是,當由於這個或其他原因需要循環時, list::erase
是可行的方法,但是它需要手動調整迭代器:請參閱: https : //stackoverflow.com/a/596180/4885321常規 for 循環將不起作用正如預期的那樣,因為(前面的代碼不好):
for(auto i = l.begin();
i!=l.end();
++i) //2nd iteration starts, we're incrementing non-existing iterator, UB!
{
if((*i) == myVal) //let's assume it's true for the first element
l.erase(i); //ok, erase it
}
因此,正確的解決方案應如下所示:
while (i != l.end()) {
if (*i == myVal) {
l.erase(i++);
// or i = l.erase(i);
// note: valid iterator is incremented before call to erase thus the new i is valid
// the node pointed to by the old one is removed
} else {
++i;
}
}
我建議在 Meyers 的Effective STL 中查找有關該主題和相關主題的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.