【问题标题】:Deleting From stl map inside a map... inside a method从地图内部的 stl 地图中删除...在方法内部
【发布时间】:2015-06-16 11:14:05
【问题描述】:

所以我正在尝试在 C++ 中实现文件系统。 我有一个包含地图的目录类。 每个目录都可以在它的地图中保存另一个目录(所以我在地图中有一个地图)

我正在尝试删除一个文件/目录,在它删除的方法中,一切都很好,但是方法完成了我的主地图没有更新......

这里是相关代码:

目录类(使用 Composite 实现):

class Directory : public FileComponent
{
private:
std::map<std::string,FileComponent*> directoryList;
public:
std::map<std::string, FileComponent*> &getMap() {
    return directoryList;
}

类文件系统:

private:
FileComponent* find(Mode mode, const std::string& newDirectory, const std::string& directoryName, std::map<std::string, FileComponent*> check);
std::map<std::string,FileComponent*> fileSystem;

};

这就是我试图做的(找到一个文件并复制它......)

void filesys::copy(const std::string& fileName, const std::string& directoryName){
//looking for file
mapitr itr = fileSystem.find(fileName);
if (itr != fileSystem.end()){
    fileSystem.erase(itr);
    //file found, looikng for directory
}
else{
    for (itr = fileSystem.begin(); itr != fileSystem.end(); itr++){
        FileComponent* toCopy = find(CopyFile, fileName, directoryName, itr->second->getMap());
        if (toCopy != nullptr)
            //found! need to copy
            break;
    }
}

}

还有我的查找方法:

FileComponent* filesys::find(Mode mode,const std::string& newDirectory, const std::string& directoryName, std::map<std::string,FileComponent*> check){
else if (mode == CopyFile){
     mapitr itr = check.find(newDirectory);
     if (itr != check.end()){
         FileComponent* toCopy = itr->second;
         check.erase(itr);
         return toCopy;
     }
     else{
         for (itr = check.begin(); itr != check.end(); itr++){
             FileComponent* toCopy;
             try{
             toCopy = find(CopyFile, newDirectory, directoryName, itr->second->getMap());
             if (toCopy != nullptr){
                 return toCopy;
             }
             }
             catch (mExceptions& e){
                 e.what();
             }

         }
         return nullptr;
     }
 }

}

在它找到并删除的函数内部,一切似乎都井井有条......但是一旦返回目录/文件仍然在我的文件系统中...... 我正在通过引用返回我的内部地图......所以我真的不知道为什么它不想工作......

提前致谢!

【问题讨论】:

    标签: c++ dictionary stl


    【解决方案1】:

    您通过 value 将参数 check(地图)传递给 find 函数。这意味着数据是复制的,您只处理副本而不是原始数据。你应该通过 *reference 来传递它:

    std::map<std::string,FileComponent*>& check
    

    在一个无关的注释中,函数名称find 不是一个好名字,它并没有真正描述函数真正做什么,即find 擦掉。

    【讨论】:

    • 愚蠢的我...是的,解决了问题...非常感谢。 find 是一个查找文件的私有方法,它有不同的模式,我也用它来插入:)
    【解决方案2】:

    filesys::find(Mode mode,
                  const std::string& newDirectory,
                  const std::string& directoryName,
                  std::map<std::string, FileComponent*> check)
    

    你通过值传递check,而不是通过引用,所以你修改了一个副本,而不是原来的。

    【讨论】:

      猜你喜欢
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2021-08-17
      • 2015-06-19
      • 2017-09-08
      • 1970-01-01
      相关资源
      最近更新 更多