You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

65 lines
1.5 KiB

/**
* Copyright (c) 2018 Niklas Rosenstein
* MIT licensed.
*
* @description Wrapping iterator to count the iteration index during the loop.
*/
#pragma once
#include "iterator.hpp"
namespace niklasrosenstein {
/**
* Implementation of the iterator behind #enumerate().
**/
template <class Iterable>
class _enumerator : public iterator<_enumerator<Iterable>> {
Iterable iter;
std::size_t index;
decltype(std::begin(iter)) iter_begin;
decltype(std::end(iter)) const iter_end;
public:
struct item {
std::size_t index;
decltype(*iter_begin) value;
};
inline _enumerator(Iterable&& iter_)
: iter(std::move(iter_)),
index(0),
iter_begin(std::begin(iter)),
iter_end(std::end(iter))
{}
// niklasrosenstein::iterator
typedef item yield_type;
inline bool has_next() const { return this->iter_begin != this->iter_end; }
inline void next() { ++this->iter_begin; ++this->index; }
inline item operator * () const { return {this->index, *this->iter_begin}; }
};
/**
* Enumerate over an iterator.
*/
template <class Iterable>
auto enumerate(Iterable& iter) -> _enumerator<movable_iterator_wrapper<Iterable>> {
return {movable_iterator_wrapper<Iterable>(iter)};
}
/**
* Enumerate over an rvalue iterator.
*/
template <class Iterable>
auto enumerate(Iterable&& iter) -> _enumerator<Iterable> {
return {std::move(iter)};
}
} // namespace niklasrosenstein