-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
range.h
126 lines (118 loc) · 3.46 KB
/
range.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#ifndef __SG_RANGE_H__
#define __SG_RANGE_H__
#include <shogun/lib/config.h>
#include <iterator>
namespace shogun
{
/** @class Helper class to spawn range iterator.
*
* Useful for C++11-style for loops:
*
* @code
* for (auto i : Range(3, 10)) { ... }
* @endcode
*/
template <typename T>
class Range
{
public:
/** Creates range with specified bounds.
* Assumes rbegin < rend.
*
* @param rbegin lower bound of range
* @param rend upper bound of range (excluding)
*/
Range(T rbegin, T rend) : m_begin(rbegin), m_end(rend)
{
}
/** @class Iterator spawned by @ref Range. */
class Iterator : public std::iterator<std::input_iterator_tag, T>
{
public:
Iterator(T value) : m_value(value)
{
}
Iterator(const Iterator& other) : m_value(other.m_value)
{
}
Iterator(Iterator&& other) : m_value(other.m_value)
{
}
Iterator& operator=(const Iterator&) = delete;
Iterator& operator++()
{
m_value++;
return *this;
}
Iterator& operator++(int)
{
Iterator tmp(*this);
++*this;
return tmp;
}
T operator*()
{
return m_value;
}
bool operator!=(const Iterator& other)
{
return this->m_value != other.m_value;
}
bool operator==(const Iterator& other)
{
return this->m_value == other.m_value;
}
private:
T m_value;
};
/** Create iterator that corresponds to the start of range.
*
* Usually called through for-loop syntax.
*/
Iterator begin() const
{
return Iterator(m_begin);
}
/** Create iterator that corresponds to the end of range.
*
* Usually called through for-loop syntax.
*/
Iterator end() const
{
return Iterator(m_end);
}
private:
/** begin of range */
T m_begin;
/** end of range */
T m_end;
};
/** Creates @ref Range with specified upper bound.
*
* @code
* for (auto i : range(100)) { ... }
* @endcode
*
* @param rend upper bound of range (excluding)
*/
template <typename T>
inline Range<T> range(T rend)
{
return Range<T>(0, rend);
}
/** Creates @ref Range with specified bounds.
*
* @code
* for (auto i : range(0, 100)) { ... }
* @endcode
*
* @param rbegin lower bound of range
* @param rend upper bound of range (excluding)
*/
template <typename T>
inline Range<T> range(T rbegin, T rend)
{
return Range<T>(rbegin, rend);
}
}
#endif /* __SG_RANGE_H__ */