我有一个递归函数,它有一个参数,该参数是对对象指针的二维矩阵的引用。我的简单问题是,我应该以什么格式在函数中传递它,这样它才能工作?
我写这段代码纯粹是为了传递我的观点,绝不代表我对递归的预期用途。
此代码检查通过矩阵到 255,255 的对角线中的 0 对象 ID 值。然后打印 0 或 -1。
typedef object* m256x256[256][256];
int x = 0;
int y = 0;
int isThereZero(m256x256 & m){
if(m[x][y]->getID() == 0){ // Each object has an ID value
return 0;
}
x++;
y++;
if(x==256){
return -1;
}
return isThereZero(/*I need to pass M byref again... what do I put here?*/);
}
int main{
object* M[256][256];
/* Initialization Code */
cout << isThereZero(M);
return EXIT_SUCCESS;
}
因此到第 256 次递归时,m 仍然是对 M 的相同引用
具体问题:我如何格式化它才能编译:
int isThereZero(m256x256 & m){
return isThereZero(/*I need to pass M byref again... what do I put here?*/);
}
最佳答案
与其使用全局 x
和 y
,不如尝试这样的事情:
bool is_there_zero(const m256x256& m, int x = 0, int y = 0)
{
if (m[x][y]->getID() == 0)
return true;
if (++y == 256) {
y = 0;
if (++x == 256) {
return false;
}
}
return is_there_zero(m, x, y);
}
所以我们修改 y
值,如果它到达行尾,我们将其重置为零并修改 x
坐标,最后终止递归都等于256,原矩阵不变。
换句话说,我们已经把它变成了一个穷人的双重 for 循环,只是增加了函数调用开销和用完堆栈的风险......
因此,我完全不确定您为什么要以这种方式进行而不只是迭代。我能看到的唯一优点是,通过对三元运算符的一些“创造性”使用,您可以将它变成一个单行 constexpr
函数,它可能在编译时被评估为一个固定的m
,但这似乎不值得这么麻烦。
编辑:重新阅读问题,我看到你只想测试前导对角线,所以它有点简单:
bool is_there_zero(const m256x256& m, int x = 0)
{
if (x == 256)
return false;
if (m[x][x]->getID() == 0)
return true;
return is_there_zero(m, ++x);
}
关于具有对象指针的 byref 二维矩阵的 C++ 递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21544310/