c++ - 如何返回指向数组中对象的指针?

标签 c++ loops return-value assimp

我正在使用 assimp 处理一些 3d 模型,我正在从任意父节点遍历子节点,寻找具有匹配字符串名称的节点。由于子项存储为数组,如果名称匹配,我需要返回指向数组中第 N 个索引处的节点的指针。我已经通过匹配字符串并将它们打印到一个 FILE 对象 (assf) 中成功找到了名称,但是尝试通过将指针返回到匹配节点来提前退出,总是返回“nullptr”。

我试过声明一个全局变量来存储临时节点指针,并在找到匹配时将匹配节点的指针复制到临时指针。这实际上确实有效,但这不是我正在寻找的解决方案,尤其是当我觉得我对递归函数及其返回值有一些根本性的误解时。或者更多。

const aiNode* fn2(const aiNode* nin, const aiString& name){
    for(unsigned int c = 0; c < nin->mNumChildren; c++){ //for every child of the node argument...
        if (nin->mChildren[c]->mName == name){ //...compare the names, and if successful enter this block
            fprintf(assf, "Found node '%s'!\n",name.C_Str());
            return nin->mChildren[c];//This IS the node i want, so why does it return null ?
        }
        else{ //The name of this node doesn't match what I'm looking for, try the next node. Repeat...
            fn2(nin->mChildren[c], name);//This WILL return the node if made called as: return fn2(nin->mChildren[c], name);
        }
    }

    fprintf(assf, "Node name (%s) not a match\n",nin->mName.C_Str());
    return nullptr;//None of the child nodes of the node passed in have a matching name!
}    

当名称匹配时,预期结果是指向数组中当前节点的指针被返回并由调用函数使用。实际结果是我总是返回 nullptr。

编辑; 谢谢 Soronel 和 Jonathan,这很有道理,帮助我想出了一个可行的解决方案。通过向函数添加一个临时变量,以下代码现在可以按预期执行;

    for (unsigned int c = 0; c < nin->mNumChildren; c++) { //for every child of the node argument...
        const aiNode* tmpnode = nullptr; //const aiNode* tmpnode = nullptr; //Store pointer to a temp node no matter what
        if (nin->mChildren[c]->mName == name) { //...compare the names, and if successful enter this block
            fprintf(assf, "Found node '%s'!\n",name.C_Str());
            tmpnode = nin->mChildren[c]; //This IS the node i want, assign it to the temp
        }
        else { //The name of this node doesn't match what I'm looking for, try the next node. Repeat...
            tmpnode = fn2(nin->mChildren[c], name); //Call this function recursively, and store it's result in the temp
        }
        if(tmpnode) return tmpnode; //Return the matched node here, OR nullptr at end of function if no match
    }
    fprintf(assf, "Node name (%s) not a match\n",nin->mName.C_Str());
    return nullptr; //None of the child nodes of the node passed in have a matching name!
}

最佳答案

您的递归调用不返回找到的值(如果有):

fn2(nin->mChildren[c], name);

需要是这样的:

const aiNode* ptr = fn2(nin->mChildren[c], name);
if(ptr)
  return ptr;

找到节点的直接函数调用没问题,问题在于如何将它传递回调用链。

关于c++ - 如何返回指向数组中对象的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57941904/

相关文章:

c++ - 使用带有字符串的 find_first_of 而不是 C++ 中的一组预定义字符

c++ - GEOSGeometry 到 geos::geom::Geometry

java - 在二维数组中打印字母?第一个字母不显示

multithreading - 多线程处理70个类似的命令并从每个命令接收输出

ios - 如何在 if 语句中成功调用 BOOL 方法?

C++系统函数挂起应用程序

c++ - 如何在 mongocxx find_one_and_update 的文档中设置值

r - 使用 R 创建完全对立的绘图

javascript - ReactJS 中的 Bootstrap 行

c++ - C++ 中缺少 return 语句仍然可以工作