0

This is a simple recursive method with caching so that the numbers will not get recalculated over and over again. I've definitely seen it work, but now it's broken and prints rubbish. I've tried reverting to working version, but just can't find any difference that could have broken it.

Why did it stop working?

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int Fibonacci_vector(int n) {
    static vector<int> cache(2, 1);
    cache.reserve(n);
    if (cache[n] == 0) {
        cache[n] = Fibonacci_vector(n-1) + Fibonacci_vector(n-2);
    }
    return cache[n];
}

int main() {
    cout << Fibonacci_vector(4);
}

UPDATE Jeez, I'm so stupid that it just hurts. I've changed if (n > cache.size()) { cache.resize(n); } to cache.reserve(n); and of course it broke everything! So sorry for my stupidity, guys.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
Akiiino
  • 1,050
  • 1
  • 10
  • 28

2 Answers2

5
  1. There's std::vector::reserve and there's also std::vector::resize. They do different things.

    cache[n] is still access out of range in both cases (one past last element in case of std::vector::resize)

  2. The condition for calculation should not try to access any cached data (out of range), it just has to compare if(n >= cache.size()).

  3. You'll need to call cache.resize(n + 1) only if the condition above is satisfied, so put it inside the if-clause.

Community
  • 1
  • 1
LogicStuff
  • 19,397
  • 6
  • 54
  • 74
1

You need to check that the element exists. Change the code like this:

int Fibonacci_vector(int n) {
    static vector<int> cache(2, 1);
    if (n >= cache.size()) {
        cache.push_back(Fibonacci_vector(n-1) + Fibonacci_vector(n-2));
    }
    return cache[n];
}
SashaMN
  • 708
  • 5
  • 16