简体   繁体   English

C ++,多次调用时输出不同的函数

[英]C++, different function output when called multiple times

I have the following code: 我有以下代码:

int countLatticePoints(const double radius, const int dimension) {
static std::vector<int> point {};
static int R = static_cast<int>(std::floor(radius));
static int latticePointCount = 0;

for(int i = -R; i <= R; i++) {

    point.push_back(i);

    if(point.size() == dimension) {
        if(PointIsWithinSphere(point,R)) latticePointCount++;
    } else {
        countLatticePoints(R, dimension);
    }

    point.pop_back();
}

return latticePointCount;
}

When I make the call countLatticePoints(2.05, 3) I get the result 13 which is correct. 当我调用countLatticePoints(2.05,3)时,得到的结果13是正确的。 Now I change the parameters and then call countLatticePoints(25.5, 1) I get 51 which is also correct. 现在,我更改参数,然后调用countLatticePoints(25.5,1),我得到了51,这也是正确的。

Now when I call countLatticePoints(2.05, 3) and countLatticePoints(25.5, 1) right after each other in the main program I get 13 and then 18 (instead of 51), I really don't understand what i'm doing wrong ? 现在,当我在主程序中彼此依次调用countLatticePoints(2.05,3)和countLatticePoints(25.5,1)时,我依次得到13和18(而不是51),我真的不明白我在做什么错吗? When I call each one individually without the other I get the correct result but when I call the functions together one after the other my results change. 当我分别调用每个函数而没有另一个函数时,会得到正确的结果,但是当我一个接一个地调用函数时,结果会改变。

You're misusing static . 您正在滥用static

The second time you call the function, you push additional values into point . 第二次调用该函数时,将其他值放入point

Edit: I hadn't spotted the recursion. 编辑:我没有发现递归。 that makes things more complex, but static is still the wrong answer. 这使事情变得更加复杂,但是static仍然是错误的答案。

I'd create a 'state' object, and split the function into two. 我将创建一个“状态”对象,并将函数分为两个部分。 One that recurses, and takes a reference to the 'state' object, and a second one which initialises the state object and calls the first. 一个递归并引用“状态”对象,第二个则初始化状态对象并调用第一个。

struct RecurState 
{
  std::vector<int> point;
  int latticePointCount

  RecurState() : latticePointCount(0)
  {
  }
}

Outer function: 外功能:

int countLatticePoints(const double radius, const int dimension) 
{
  RecurState state;
  return countLatticeRecurse(radius, dimension, state)
} 

Recursive function 递归函数

int countLatticeRecurse(const double radius, const int dimension, RecurseState &state)
{
  ...
}  

在第一个函数调用中,局部静态变量仅被初始化一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM