问题:
我正在编写一个简单的文件管理器应用程序。在这个程序中,我有一个“目录”类:
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())