alpaqa 1.0.0a12
Nonconvex constrained optimization
Loading...
Searching...
No Matches
enumerate.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <ranges>
4#include <utility>
5
6namespace alpaqa::util {
7
8template <class Rng>
9struct enumerate_t : std::ranges::view_interface<enumerate_t<Rng>> {
11
12 // P2325R3: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2325r3.html
13 enumerate_t() = default;
14 enumerate_t(Rng rng) : rng{std::forward<Rng>(rng)} {}
15
16 using begin_t = decltype(std::ranges::begin(std::as_const(rng)));
17 using end_t = decltype(std::ranges::end(std::as_const(rng)));
18
19 struct sentinel_t {
21 };
22
23 struct iter_t {
24 // P2325R3: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2325r3.html
25 iter_t() = default;
26 iter_t(begin_t &&it) : it{std::forward<begin_t>(it)} {}
27
28 using index_t = std::ranges::range_difference_t<Rng>;
31
32 using difference_type = std::ptrdiff_t;
33 using value_type = std::tuple<index_t, decltype(*it)>;
34
35 bool operator!=(sentinel_t s) const { return s.it != it; }
36 bool operator==(sentinel_t s) const { return s.it == it; }
37 // TODO: For Clang bug
38 friend bool operator!=(sentinel_t s, const iter_t &i) { return i != s; }
39 friend bool operator==(sentinel_t s, const iter_t &i) { return i == s; }
40
42 ++it;
43 ++index;
44 return *this;
45 }
46 iter_t operator++(int) const {
47 auto tmp = *this;
48 ++*this;
49 return tmp;
50 }
51
52 value_type operator*() const { return {index, *it}; }
53 };
54
56 return iter_t{std::ranges::begin(rng)};
57 }
58 auto end() const
59 // -> std::sentinel_for<iter_t> auto
60 {
61 return sentinel_t{std::ranges::end(rng)};
62 }
63};
64
65template <class Rng>
66auto enumerate(Rng &&rng) {
67 return enumerate_t<std::views::all_t<Rng>>{std::forward<Rng>(rng)};
68}
69
70} // namespace alpaqa::util
auto enumerate(Rng &&rng)
Definition enumerate.hpp:66
constexpr const auto inf
Definition config.hpp:85
std::tuple< index_t, decltype(*it)> value_type
Definition enumerate.hpp:33
friend bool operator==(sentinel_t s, const iter_t &i)
Definition enumerate.hpp:39
friend bool operator!=(sentinel_t s, const iter_t &i)
Definition enumerate.hpp:38
std::ranges::range_difference_t< Rng > index_t
Definition enumerate.hpp:28
bool operator!=(sentinel_t s) const
Definition enumerate.hpp:35
bool operator==(sentinel_t s) const
Definition enumerate.hpp:36
auto begin() const -> std::input_or_output_iterator auto
Definition enumerate.hpp:55
decltype(std::ranges::end(std::as_const(rng))) end_t
Definition enumerate.hpp:17
decltype(std::ranges::begin(std::as_const(rng))) begin_t
Definition enumerate.hpp:16