简体   繁体   中英

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. Now I change the parameters and then call countLatticePoints(25.5, 1) I get 51 which is also correct.

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 ? 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 .

The second time you call the function, you push additional values into point .

Edit: I hadn't spotted the recursion. that makes things more complex, but static is still the wrong answer.

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)
{
  ...
}  

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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