为什么此代码打印垃圾

Why does this code print rubbish?

本文关键字:打印 代码 为什么      更新时间:2023-10-16
这是一种

简单的递归缓存方法,因此不会一遍又一遍地重新计算数字。我肯定看到它有效,但现在它坏了,打印垃圾。我尝试恢复到工作版本,但找不到任何可能破坏它的区别。

为什么它停止工作?

#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);
}

更新哎呀,我太笨了,只是很痛。我已经if (n > cache.size()) { cache.resize(n); }改成了cache.reserve(n);,当然它破坏一切!伙计们,为我的愚蠢感到抱歉。

  1. std::vector::reserve,也有std::vector::resize.他们做不同的事情。

    在这两种情况下,cache[n] 仍然超出范围(在 std::vector::resize 的情况下,最后一个元素过去一个)

  2. 计算条件不应尝试访问任何缓存数据(超出范围),它只需要比较if(n >= cache.size())

  3. 只有在满足上述条件时,才需要调用cache.resize(n + 1),因此请将其放在 if -子句中。

您需要检查该元素是否存在。像这样更改代码:

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];
}