I want to create a custom iterator shell, for example enumerate: given a pair of iterators by type T, it will return an iterable type std::pair<const int, T&>, where the first element of the pair takes values โโ0, 1, 2, etc.
I had a problem to find out what should be value_typeand referencemy iterator. I want to support two behaviors:
First, referring to the values โโof the base sequence:
for (auto& kv: enumerate(my_vec)) {
kv.second = kv.first;
}
(view std::iota);
Secondly, by making a copy of the value:
std::vector<int> a{10, 20, 30};
auto copy = *enumerate(a).begin();
a[0] = 15;
std::cout << copy.first << " " << copy.second;
, Iterator::operator*(). std::pair<const int, T&>, . std::pair<const int, T>, . value_type, reference pointer typedefs ?
. , .
template<typename T>
struct Iterator {
using TT = typename std::iterator_traits<T>::value_type;
using value_type = std::pair<const int, TT>;
using reference = std::pair<const int&, typename std::iterator_traits<T>::reference>;
using pointer = value_type*;
using iterator_category = std::forward_iterator_tag;
using difference_type = std::ptrdiff_t;
std::pair<int, T> it;
Iterator(T iterator) : it(0, iterator) {}
bool operator==(const Iterator& other) const { return it.second == other.it.second; }
bool operator!=(const Iterator& other) const { return it.second != other.it.second; }
reference operator*() { return { it.first, *it.second }; }
Iterator& operator++() { ++it.first; ++it.second; return *this; }
};
P.S. , boost:: adapters:: index .