forked from ryanhaining/cppitertools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepeat.hpp
More file actions
79 lines (62 loc) · 1.94 KB
/
repeat.hpp
File metadata and controls
79 lines (62 loc) · 1.94 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
#ifndef REPEAT_HPP__
#define REPEAT_HPP__
#include <iterator>
#include <utility>
namespace iter {
// must me negative
constexpr int INFINITE_REPEAT = -1;
template <typename T>
class Repeater;
template <typename T>
Repeater<T> repeat(T&&, int count =INFINITE_REPEAT);
template <typename T>
class Repeater {
friend Repeater repeat<T>(T&&, int);
private:
T elem;
int count;
Repeater(T e, int c)
: elem(std::forward<T>(e)),
count{c}
{ }
public:
class Iterator {
private:
T& elem;
int count;
public:
Iterator(T& e, int c)
: elem{e},
count{c}
{ }
// count down to 0
// INFINITE_REPEAT will be negative, and in that case
// the value is never decremented, it will always compare
// != to an end iterator
Iterator& operator++() {
if (this->count > 0) {
--this->count;
}
return *this;
}
bool operator!=(const Iterator& other) const {
return this->count != other.count ||
&this->elem != &other.elem;
}
T& operator*() {
return this->elem;
}
};
Iterator begin() {
return {this->elem, this->count};
}
Iterator end() {
return {this->elem, 0};
}
};
template <typename T>
Repeater<T> repeat(T&& e, int count) {
return {std::forward<T>(e), count};
}
}
#endif //REPEAT_HPP__