在递归函数内计数

时间:2016-05-19 21:27:57

标签: c++ c++11 recursion

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时工作正常,但现在如果我再次调用该函数,它会在我第一次调用count时添加到先前的countLatticePoints值。我知道这是因为静态限定符的行为方式。有没有什么办法可以在我打电话给第二个呼叫之后将一个呼叫结束后将count变量重置为0?我当然不想使用全局变量,还有其他方法可以在这种情况下工作吗?

3 个答案:

答案 0 :(得分:2)

计数作为参数传递;给它一个默认值0,所以初始调用不必提供它。这会满足您的需求吗?

答案 1 :(得分:2)

您不需要任何静态变量或其他参数。这就是你需要的。

int countLatticePoints(std::vector<int> &point, const double &radius, const int &dimension) {
    int count = 0;
    const int iRadius = std::floor(radius);
    for(int i = -iRadius; i <= iRadius; i++) {
        point.push_back(i);
        if(point.size() == dimension){
            if (isPointWithinSphere(point, radius))
                count++;
        } else
            count += countLatticePoints(point, radius, dimension);
        point.pop_back();
    }

    return count;
}

在旁注中,您不需要传递int或double作为参考。

答案 2 :(得分:1)

您可以使用辅助函数来完成您想要的操作,如下所示:

void countLatticePoints(std::vector<int> &point, const double &radius, const int &dimension, int& count) {
    const int int_radius = static_cast<int>(std::floor(radius));
    for(int i = -int_radius; i <= int_radius; i++) {
        point.push_back(i);

        if(point.size() == dimension){
            if(isPointWithinSphere(point, radius)) count++;
        }else countLatticePoints(point, radius, dimension, count);

        point.pop_back();
    }
}

int countLatticePoints(std::vector<int> &point, const double &radius, const int &dimension) {
    int count = 0;    
    countLatticePoints(point, radius, dimension, count);
    return count;
}