forked from alabuzhev/cppitertools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
enumerate.hpp
107 lines (84 loc) · 2.63 KB
/
enumerate.hpp
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
#ifndef ITER_ENUMERATE_H_
#define ITER_ENUMERATE_H_
#include "internal/iterbase.hpp"
#include <utility>
#include <iterator>
#include <functional>
#include <type_traits>
namespace iter {
namespace impl {
template <typename Container>
class Enumerable;
}
template <typename Container>
impl::Enumerable<Container> enumerate(Container&&, std::size_t = 0);
}
template <typename Container>
class iter::impl::Enumerable {
private:
Container container;
const std::size_t start;
// The only thing allowed to directly instantiate an Enumerable is
// the enumerate function
friend Enumerable iter::enumerate<Container>(Container&&, std::size_t);
// for IterYield
using BasePair = std::pair<std::size_t, iterator_deref<Container>>;
// Value constructor for use only in the enumerate function
Enumerable(Container&& in_container, std::size_t in_start)
: container(std::forward<Container>(in_container)), start{in_start} {}
public:
Enumerable(Enumerable&&) = default;
// "yielded" by the Enumerable::Iterator. Has a .index, and a
// .element referencing the value yielded by the subiterator
class IterYield : public BasePair {
public:
using BasePair::BasePair;
typename BasePair::first_type& index = BasePair::first;
typename BasePair::second_type& element = BasePair::second;
};
// Holds an iterator of the contained type and a size_t for the
// index. Each call to ++ increments both of these data members.
// Each dereference returns an IterYield.
class Iterator : public std::iterator<std::input_iterator_tag, IterYield> {
private:
iterator_type<Container> sub_iter;
std::size_t index;
public:
Iterator(iterator_type<Container>&& si, std::size_t start)
: sub_iter{std::move(si)}, index{start} {}
IterYield operator*() {
return {this->index, *this->sub_iter};
}
ArrowProxy<IterYield> operator->() {
return {**this};
}
Iterator& operator++() {
++this->sub_iter;
++this->index;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {std::begin(this->container), start};
}
Iterator end() {
return {std::end(this->container), start};
}
};
template <typename Container>
iter::impl::Enumerable<Container> iter::enumerate(
Container&& container, std::size_t start) {
return {std::forward<Container>(container), start};
}
#endif