为什么此代码打印垃圾
Why does this code print rubbish?
这是一种
简单的递归缓存方法,因此不会一遍又一遍地重新计算数字。我肯定看到它有效,但现在它坏了,打印垃圾。我尝试恢复到工作版本,但找不到任何可能破坏它的区别。
为什么它停止工作?
#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);
,当然它破坏了一切!伙计们,为我的愚蠢感到抱歉。
-
有
std::vector::reserve
,也有std::vector::resize
.他们做不同的事情。在这两种情况下,
cache[n]
仍然超出范围(在std::vector::resize
的情况下,最后一个元素过去一个) -
计算条件不应尝试访问任何缓存数据(超出范围),它只需要比较
if(n >= cache.size())
。 -
只有在满足上述条件时,才需要调用
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];
}
相关文章:
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 我应该如何修改此代码以使用给定字符串中的字母打印菱形图案
- C ++如何使用UTF8十六进制代码打印UTF8符号?
- 如何使代码打印文本文件中的第一行?
- 如何修改代码以打印出数组 v2
- Printf 命令不打印时添加了查找常见除数的新代码
- 使用用户输入打印 6X10 矩阵的代码 - C++
- 任何人都可以弄清楚这段代码如何显示运行错误?它打印无限时间 -1 以及正确答案
- 我编写了以下代码来读取C++矩阵,然后打印其行和列.我收到此错误
- 无法在野牛代码中打印正确的值
- C++:正则表达式匹配代码,打印多个匹配项?
- 如何在c++中仅使用for循环打印此代码的垂直直方图
- 为什么我的代码在要求打印长度和宽度的值后不接受多个输入?
- 这个随机字符串打印代码有什么问题?
- 打印C 代码执行逐步执行
- 打印代码 128 C 条形码通过与 OPOS 公共控件 1.8 交互C++代码
- 这个打印代码是如何工作的
- 我的堆栈的打印代码出现分段错误,不知道我哪里出错了。
- 如何打印代码的执行时间