Yes, you can, just take a little massage;)
The trick is to use the composition: instead of iterating over the container directly, you "zip" its index along the way.
Specialized zipper code:
template <typename T> struct iterator_extractor { typedef typename T::iterator type; }; template <typename T> struct iterator_extractor<T const> { typedef typename T::const_iterator type; }; template <typename T> class Indexer { public: class iterator { typedef typename iterator_extractor<T>::type inner_iterator; typedef typename std::iterator_traits<inner_iterator>::reference inner_reference; public: typedef std::pair<size_t, inner_reference> reference; iterator(inner_iterator it): _pos(0), _it(it) {} reference operator*() const { return reference(_pos, *_it); } iterator& operator++() { ++_pos; ++_it; return *this; } iterator operator++(int) { iterator tmp(*this); ++*this; return tmp; } bool operator==(iterator const& it) const { return _it == it._it; } bool operator!=(iterator const& it) const { return !(*this == it); } private: size_t _pos; inner_iterator _it; }; Indexer(T& t): _container(t) {} iterator begin() const { return iterator(_container.begin()); } iterator end() const { return iterator(_container.end()); } private: T& _container; };
And using it:
#include <iostream> #include <iterator> #include <limits> #include <vector> // Zipper code here int main() { std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9}; for (auto p: index(v)) { std::cout << p.first << ": " << p.second << "\n"; } }
You can see it on ideone , although it lacks for-range loop support, so it is less cute.
EDIT:
Just remembered that I should check Boost.Range more often. Unfortunately, the zip range was not found, but I found perl: boost::adaptors::indexed . However, access to the iterator requires access to the index. Shame: x
Otherwise, with counting_range and a common zip I am sure that something interesting could be done ...
In an ideal world, I would suggest:
int main() { std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9}; for (auto tuple: zip(iota(0), v)) { std::cout << tuple.at<0>() << ": " << tuple.at<1>() << "\n"; } }
With zip automatically creating a view in the form of a set of link tuples and iota(0) just creating a “false” range that starts at 0 and just counts to infinity (or, well, the maximum of its type ...).