如何从C++中的for循环内的列表中删除

有没有办法删除循环遍历该列表的 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

   


以上是如何从C++中的for循环内的列表中删除的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>