-
Notifications
You must be signed in to change notification settings - Fork 939
Expand file tree
/
Copy pathmain.cpp
More file actions
39 lines (33 loc) · 1.12 KB
/
main.cpp
File metadata and controls
39 lines (33 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "../exercise.h"
// READ: 析构函数 <https://zh.cppreference.com/w/cpp/language/destructor>
// READ: RAII <https://learn.microsoft.com/zh-cn/cpp/cpp/object-lifetime-and-resource-management-modern-cpp?view=msvc-170>
/// @brief 任意缓存容量的斐波那契类型。
/// @details 可以在构造时传入缓存容量,因此需要动态分配缓存空间。
class DynFibonacci {
size_t *cache;
int cached;
public:
// 实现动态设置容量的构造器
DynFibonacci(int capacity): cache(new size_t[capacity]()), cached(2) {
cache[0] = 0;
cache[1] = 1;
}
// 实现析构器,释放缓存空间
~DynFibonacci() {
delete[] cache;
}
// 实现正确的缓存优化斐波那契计算
size_t get(int i) {
while (cached <= i) {
cache[cached] = cache[cached - 1] + cache[cached - 2];
++cached;
}
return cache[i];
}
};
int main(int argc, char **argv) {
DynFibonacci fib(12);
ASSERT(fib.get(10) == 55, "fibonacci(10) should be 55");
std::cout << "fibonacci(10) = " << fib.get(10) << std::endl;
return 0;
}