forked from alabuzhev/cppitertools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
permutations.hpp
109 lines (88 loc) · 2.65 KB
/
permutations.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
108
109
#ifndef ITER_PERMUTATIONS_HPP_
#define ITER_PERMUTATIONS_HPP_
#include "internal/iterbase.hpp"
#include "internal/iteratoriterator.hpp"
#include <algorithm>
#include <vector>
#include <utility>
#include <iterator>
namespace iter {
namespace impl {
template <typename Container>
class Permuter;
}
template <typename Container>
impl::Permuter<Container> permutations(Container&&);
}
template <typename Container>
class iter::impl::Permuter {
private:
Container container;
using IndexVector = std::vector<iterator_type<Container>>;
using Permutable = IterIterWrapper<IndexVector>;
friend Permuter iter::permutations<Container>(Container&&);
Permuter(Container&& in_container)
: container(std::forward<Container>(in_container)) {}
public:
Permuter(Permuter&&) = default;
class Iterator : public std::iterator<std::input_iterator_tag, Permutable> {
private:
static constexpr const int COMPLETE = -1;
static bool cmp_iters(const iterator_type<Container>& lhs,
const iterator_type<Container>& rhs) noexcept {
return *lhs < *rhs;
}
Permutable working_set;
int steps{};
public:
Iterator(
iterator_type<Container>&& sub_iter, iterator_type<Container>&& sub_end)
: steps{sub_iter != sub_end ? 0 : COMPLETE} {
// done like this instead of using vector ctor with
// two iterators because that causes a substitution
// failure when the iterator is minimal
while (sub_iter != sub_end) {
this->working_set.get().push_back(sub_iter);
++sub_iter;
}
std::sort(std::begin(working_set.get()), std::end(working_set.get()),
cmp_iters);
}
Permutable& operator*() {
return this->working_set;
}
Permutable* operator->() {
return &this->working_set;
}
Iterator& operator++() {
++this->steps;
if (!std::next_permutation(std::begin(working_set.get()),
std::end(working_set.get()), cmp_iters)) {
this->steps = COMPLETE;
}
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->steps == other.steps;
}
};
Iterator begin() {
return {std::begin(this->container), std::end(this->container)};
}
Iterator end() {
return {std::end(this->container), std::end(this->container)};
}
};
template <typename Container>
iter::impl::Permuter<Container> iter::permutations(Container&& container) {
return {std::forward<Container>(container)};
}
#endif