-
Notifications
You must be signed in to change notification settings - Fork 939
Expand file tree
/
Copy pathmain.cpp
More file actions
87 lines (73 loc) · 2.76 KB
/
main.cpp
File metadata and controls
87 lines (73 loc) · 2.76 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include "../exercise.h"
// READ: 左值右值(概念)<https://learn.microsoft.com/zh-cn/cpp/c-language/l-value-and-r-value-expressions?view=msvc-170>
// READ: 左值右值(细节)<https://zh.cppreference.com/w/cpp/language/value_category>
// READ: 关于移动语义 <https://learn.microsoft.com/zh-cn/cpp/cpp/rvalue-reference-declarator-amp-amp?view=msvc-170#move-semantics>
// READ: 如果实现移动构造 <https://learn.microsoft.com/zh-cn/cpp/cpp/move-constructors-and-move-assignment-operators-cpp?view=msvc-170>
// READ: 移动构造函数 <https://zh.cppreference.com/w/cpp/language/move_constructor>
// READ: 移动赋值 <https://zh.cppreference.com/w/cpp/language/move_assignment>
// READ: 运算符重载 <https://zh.cppreference.com/w/cpp/language/operators>
class DynFibonacci {
size_t *cache;
int cached;
int capacity;
public:
// TODO: 实现动态设置容量的构造器
DynFibonacci(int capacity): cache(new size_t [capacity]), cached(0), capacity(capacity) {
cache[0] = 0;
cache[1] = 1;
cached = 2;
}
// TODO: 实现移动构造器
DynFibonacci(DynFibonacci &&other) noexcept : cache(other.cache), cached(other.cached), capacity(other.capacity) {
other.cache = nullptr;
other.cached = 0;
other.capacity = 0;
}
// TODO: 实现移动赋值
// NOTICE: ⚠ 注意移动到自身问题 ⚠
DynFibonacci &operator=(DynFibonacci &&other) noexcept {
if (this != &other) {
delete[] cache;
cache = other.cache;
cached = other.cached;
capacity = other.capacity;
other.cache = nullptr;
other.cached = 0;
other.capacity = 0;
}
return *this;
}
// TODO: 实现析构器,释放缓存空间
~DynFibonacci() {
delete[] cache;
}
// TODO: 实现正确的缓存优化斐波那契计算
size_t operator[](int i) {
for (; cached <= i; ++cached) {
cache[cached] = cache[cached - 1] + cache[cached - 2];
}
return cache[i];
}
// NOTICE: 不要修改这个方法
size_t operator[](int i) const {
ASSERT(i <= cached, "i out of range");
return cache[i];
}
// NOTICE: 不要修改这个方法
bool is_alive() const {
return cache;
}
};
int main(int argc, char **argv) {
DynFibonacci fib(12);
ASSERT(fib[10] == 55, "fibonacci(10) should be 55");
DynFibonacci const fib_ = std::move(fib);
ASSERT(!fib.is_alive(), "Object moved");
ASSERT(fib_[10] == 55, "fibonacci(10) should be 55");
DynFibonacci fib0(6);
DynFibonacci fib1(12);
fib0 = std::move(fib1);
fib0 = std::move(fib0);
ASSERT(fib0[10] == 55, "fibonacci(10) should be 55");
return 0;
}