【问题标题】:Why does this code print rubbish?为什么这段代码打印垃圾?
【发布时间】:2023-03-25 13:17:01
【问题描述】:

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

为什么它停止工作了?

#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 &gt; cache.size()) { cache.resize(n); } 更改为cache.reserve(n);当然它破坏了一切!对不起,伙计们,我的愚蠢。

【问题讨论】:

  • 这不会编译。您正在尝试访问您无权访问的内存。
  • cache[n] 从 1 开始什么时候会是 0?
  • @TarikNeaj, It compiles.
  • 出于某种原因不适合我。使用 Visual Studio 2013。
  • @OP,你可能想要std::unordered_map

标签: c++ caching recursion vector fibonacci


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    1. std::vector::reserve,还有std::vector::resizeThey do different things.

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多