-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrange-iter.h
88 lines (78 loc) · 1.68 KB
/
range-iter.h
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
88
// Copyright © 2020 Artyom Tokarev. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include <cstdlib>
#include <cmath>
namespace itr {
enum class dir {
forward,
reverse
};
// begin < end:
// [begin; end)
// if forward: begin, begin+1, ... end-1
// else : end-1, end-2, ... begin
//
// begin > end:
// [end; begin)
// if forward: begin, begin-1, ... end+1
// else : end+1, end+2, ... begin
//
template <typename Signed>
class range_iter {
public:
Signed front() const {
return m_begin;
}
Signed back() const {
return m_end - m_step;
}
Signed begin() const {
return m_begin;
}
Signed end() const {
return m_end;
}
Signed next() {
return m_current + m_step;
}
Signed prev() {
return m_current - m_step;
}
bool has_ended() const {
return m_current == m_end;
}
range_iter& operator++() {
next();
return *this;
}
Signed operator*() {
return m_current;
}
void init(Signed begin, Signed end, dir dir) {
if (begin > end) {
auto buf = begin;
begin = end + 1;
end = buf + 1;
}
if (dir == dir::forward) {
m_begin = begin;
m_end = end;
m_step = 1;
} else {
m_begin = end - 1;
m_end = begin - 1;
m_step = -1;
}
m_current = m_begin;
}
range_iter(Signed begin, Signed end, dir dir = dir::forward) {
init(begin, end, dir);
}
private:
Signed m_begin;
Signed m_end;
Signed m_current;
Signed m_step;
};
} // namespace itr