【发布时间】:2016-05-19 21:27:56
【问题描述】:
int countLatticePoints(std::vector<int> &point, const double &radius, const int &dimension) {
static int count = 0;
for(int i = -(static_cast<int>(std::floor(radius))); i <= static_cast<int>(std::floor(radius)); i++) {
point.push_back(i);
if(point.size() == dimension){
if(isPointWithinSphere(point, radius)) count++;
}else countLatticePoints(point, radius, dimension);
point.pop_back();
}
return count;
}
我有上面的递归函数,如果条件isPointWithinSphere( ... ) 为真,我想为它增加一些变量。我最初的方法是声明一个名为count 的静态变量,以便它通过每个递归调用来维护计数。好的,当我第一次调用函数countLatticePoints 时这很好用,但是现在如果我再次调用该函数,它会在我第一次调用countLatticePoints 时添加到先前的count 值。我知道这是由于静态限定符的行为方式而发生的。有什么方法可以在我调用第二个调用完成之前将count 变量重置回 0 吗?我当然不想使用全局变量,有没有其他方法可以在这种情况下工作?
【问题讨论】:
-
您不需要传递原生类型,例如
double或int作为const &。常量引用通常用于传递大对象或类 -
"当我第一次调用函数 countLatticePoints 时,这很好用,但现在如果我再次调用该函数,它会在我第一次调用 countLatticePoints 时添加到先前的计数值。" - 如果这不是你想要的行为,你想要什么?函数第一次从外面调用并返回后,你的计数应该是多少?在第二次调用并返回后,您的计数应该是多少?
-
@user31264 第一次调用后是 19,第二次调用应该是 51 而不是 19 + 51
-
在这种情况下还有其他方法可以工作吗? 是的,绝对!您不需要递归来创建排列。请参阅我对您之前问题的回答。 stackoverflow.com/a/37326790/224704