c++ - 如何使用迭代器有条件地从列表中删除元素?

标签 c++ linked-list listiterator

问题:

我正在编写一个简单的文件管理器应用程序。在这个程序中,我有一个“目录”类:

class Directory
{
public:
    Directory(string address, string directoryname)
    {
        this->path = address;
        this->name = directoryname;
    }
    string GetFullPath(){ return path == "/" ? path + name : path + "/" + name; }
    string path;
    string name;
    string user;
};

和目录对象的链表:

list<Directory*> DirectoryList;

我想在 Linux 中执行 "rm -r directorypath" shell 命令,因此我需要浏览列表并删除“directorypath”目录及其所有子目录。问题是我不知道如何浏览链接列表并删除父目录为“directorypath”的所有目录。我试过这两种方法:

方法一:

此方法遇到运行时错误,因为它在第一次删除后无法再访问列表。

for (auto address : DirectoryList)
        if (address->GetFullPath() == directorypath)
        {
            for (auto subdirectory : DirectoryList)
            if (subdirectory ->path == address->GetFullPath())
                DirectoryList.remove(subdirectory );
        }

方法二:

for (auto address : DirectoryList)
        if (address->GetFullPath() == directorypath)
        {
            for (auto it = DirectoryList.begin(); it != DirectoryList.end();)
                it = DirectoryList.erase(it);
            return true;
        }

此方法即使在删除后也可以完美地访问所有元素,但我不知道如何使用迭代器 it 检查此 if 条件:

if (subdirectory ->path == address->GetFullPath())

最佳答案

您的方法 1 失败了,因为 std::list.remove(val) 删除了列表中比较等于 val 的所有元素。你调用一次就完成了。 for() 循环不应该存在,它不是预期的使用方式。很好的例子是 here .

请注意,此方法将修改您的容器及其大小。你需要在这里小心并确保你的迭代器在调用 erase 之后仍然有效。我的直觉是迭代器确实失效了,这就是你出错的原因。

您的方法 2 看起来几乎没问题。首先,fallow niceguy 的检查条件的建议:

if ((*it).path == address->GetFullPath())

现在,请记住,删除 会将迭代器更新为指向您删除的迭代器之后的位置。这算作迭代器 it 的一次更新。它将在 for 循环中进一步更新,但这不是您想要的(即每次迭代两次更新意味着您将跳过一些元素)。你可以尝试这样的事情:

auto it = DirectoryList.begin()
while (it != DirectoryList.end())
{
   if ((*it).path == address->GetFullPath())
       DirectoryList.erase(it);
}

关于c++ - 如何使用迭代器有条件地从列表中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30682195/

相关文章:

Java - 使用 ListIterator .hasNext() 的无限循环

c++ - 如何避免填充以使结构不使用额外的字节

c++ - const 迭代器依赖于 begin() 函数

c++ - 将中等数量的 T* static_casting 为 void* 时发生访问冲突

c++ - 链表更改节点而不是添加另一个节点

java - 从列表中删除字符串并在java中排序

java - 使用ListIterator删除重复项

c++ - CMake 找到了 Boost 但未找到请求的库

Java - 这个对象什么时候卸载?

C++ 程序在读取 NULL 引用时崩溃