3

问题:

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

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;

我想"rm -r directorypath"在linux中实现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;
        }

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

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

1 回答 1

1

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

请注意,此方法将修改您的容器及其大小。您需要在这里小心并确保您的迭代器在调用erase. 我的直觉是,迭代器确实无效,这就是你得到错误的原因。

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

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

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

auto it = DirectoryList.begin()
while (it != DirectoryList.end())
{
   if ((*it).path == address->GetFullPath())
       DirectoryList.erase(it);
}
于 2015-06-06T12:17:16.177 回答