This repository was archived by the owner on Nov 15, 2022. It is now read-only.
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
101 lines (81 loc) · 2.61 KB
/
Copy pathrepeat.hpp
File metadata and controls
101 lines (81 loc) · 2.61 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#ifndef ITER_REPEAT_HPP_
#define ITER_REPEAT_HPP_
#include <iterator>
#include <type_traits>
#include <utility>
namespace iter {
// must be negative
constexpr int INFINITE_REPEAT = -1;
template <typename T>
class Repeater;
template <typename T>
Repeater<T> repeat(T&&);
template <typename T>
Repeater<T> repeat(T&&, int);
template <typename T>
class Repeater {
friend Repeater repeat<T>(T&&);
friend Repeater repeat<T>(T&&, int);
private:
using TPlain = std::remove_reference_t<T>;
T elem;
int count;
Repeater(T e, int c)
: elem(std::forward<T>(e)),
count{c}
{ }
public:
class Iterator
: public std::iterator<std::input_iterator_tag, TPlain>
{
private:
TPlain* elem;
int count;
public:
Iterator(TPlain* 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;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->count == other.count;
}
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) {
return {std::forward<T>(e), INFINITE_REPEAT};
}
template <typename T>
Repeater<T> repeat(T&& e, int count) {
// if count is negative, pass 0 instead
return {std::forward<T>(e), count < 0 ? 0 : count};
}
}
#endif