-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy path8.2optional管理可选值.cpp
66 lines (57 loc) · 1.3 KB
/
8.2optional管理可选值.cpp
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
#include"print.h"
#include<optional>
#if 0
factor_t factor(long n) {
struct factor_t {
bool is_prime;
long factor;
};
factor_t r{};
for (long i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
r.is_prime = false;
r.factor = i;
return r;
}
}
r.is_prime = true;
}
#endif
std::optional<long>factor(long n) {
for (long i = 2; i <= n / 2; ++i) {
if (n % i == 0)return { i };
}
return {};
}
std::optional<int> operator+(const std::optional<int>& a, const std::optional<int>& b) {
if (a && b)return *a + *b;
else return {};
}
std::optional<int> operator+(const std::optional<int>& a, const int b) {
if (a)return *a + b;
else return {};
}
int main() {
long a{ 42 };
long b{ 73 };
auto x = factor(a);
auto y = factor(b);
if (x)print("lowest factor of {} is {} \n", a, *x);
else print("{} is prime\n", a);
if (y)print("lowest factor of {} is {} \n", a, *y);
else print("{} is prime\n", b);
std::optional<int>a2{ 42 };
print("{}\n", *a2);
if (a2)print("{}\n", *a2);
else print("no value\n");
{
std::optional<int> a{ 42 };
std::optional<int> b{ 73 };
auto sum{ a + b };
if (sum)print("{} + {} = {}\n", *a, *b, *sum);
else print("NAN\n");
}
(void)a2.has_value();//判断是否有值
(void)a2.value();//和*作用一样,取值
a2.reset();//销毁值,重置可选对象状态
}