1

I'm trying to iterate through multiple lists to find a "Directory". If I have a directory structure such as: /A/B/C

/A/D/F

It seems to work if I look for B or C, but fails for D and F. I think this is because when it encounters a situation where it is searching down a list and it doesn't find the correct Directory then it doesn't know what to return (or if I uncomment the return NULL it returns null, which I don't want it to because it doesn't mean it's not technically found).

I.E. If I search for F, it will search A/B/C and not know what to return.

Is there a way to hold off on the return value until it finds a directory or until it is finished looking?

Directory* search_tree_for_dir(string dir_name) {
            for(list<Directory*>::iterator iter = this->l_dir.begin(); iter != this->l_dir.end(); iter++) {
                  // Base case: if directory found then return
                  if((*iter)->name == dir_name){
                      return *iter;
                  }
                  if(*iter != NULL) { 
                      return (*iter)->search_tree_for_dir(dir_name);
                  }
              } 
              //return NULL;
          }
4

1 回答 1

2

您要做的是检查递归调用的返回值,并查看它返回的内容。例如:

Directory *ret = (*iter)->search_tree_for_dir(dir_name);
if (ret) {
    return ret;
}

这样,如果递归调用返回的不是NULL,您将传递它。如果它没有找到任何东西(即它返回NULL),那么您就不要传递它,而是继续搜索。

于 2013-04-18T22:06:36.780 回答