-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterator.cc
64 lines (55 loc) · 1.38 KB
/
iterator.cc
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
//
// Design pattern # iterator
// Lets you iterator the object without exposing how it stored
//
// g++ -std=c++17 -Wall -Wextra -o iterator iterator.cc
//
#include <iostream>
#include <array>
constexpr int size = 3;
struct stack {
std::array<int, size> vec;
int curr = 0;
bool is_empty() { return curr == 0; }
bool is_full() { return curr == size; }
void push(int num) {
if (!is_full())
vec[curr++] = num;
else
throw std::length_error("full");
}
int top() {
if (!is_empty())
return vec[curr - 1];
throw std::out_of_range("nothing to pop");
}
int pop() {
if (!is_empty()) {
int ret = vec[curr - 1];
--curr;
return ret;
}
throw std::out_of_range("nothing to pop");
}
};
//
// Entry function
//
int main() {
std::cout << "Design pattern # iterator\n";
stack st;
std::cout << "Full: " << std::boolalpha << st.is_full() << '\n';
std::cout << "Empty: " << std::boolalpha << st.is_empty() << '\n';
std::cout << "Push 2 elements\n";
st.push(1);
st.push(2);
st.push(3);
std::cout << "Full: " << std::boolalpha << st.is_full() << '\n';
std::cout << "Empty: " << std::boolalpha << st.is_empty() << '\n';
std::cout << "Pop 2 elements\n";
st.pop();
st.pop();
std::cout << "Full: " << std::boolalpha << st.is_full() << '\n';
std::cout << "Empty: " << std::boolalpha << st.is_empty() << '\n';
return 0;
}