fork(3) download
  1. #include <iostream>
  2. #include <iterator>
  3. #include <limits>
  4. #include <vector>
  5.  
  6.  
  7. template <typename T>
  8. struct iterator_extractor { typedef typename T::iterator type; };
  9.  
  10. template <typename T>
  11. struct iterator_extractor<T const> { typedef typename T::const_iterator type; };
  12.  
  13.  
  14. template <typename T>
  15. class Indexer {
  16. public:
  17. class iterator {
  18. typedef typename iterator_extractor<T>::type inner_iterator;
  19.  
  20. typedef typename std::iterator_traits<inner_iterator>::reference inner_reference;
  21. public:
  22. typedef std::pair<size_t, inner_reference> reference;
  23.  
  24. iterator(inner_iterator it): _pos(0), _it(it) {}
  25.  
  26. reference operator*() const { return reference(_pos, *_it); }
  27.  
  28. iterator& operator++() { ++_pos; ++_it; return *this; }
  29. iterator operator++(int) { iterator tmp(*this); ++*this; return tmp; }
  30.  
  31. bool operator==(iterator const& it) const { return _it == it._it; }
  32. bool operator!=(iterator const& it) const { return !(*this == it); }
  33.  
  34. private:
  35. size_t _pos;
  36. inner_iterator _it;
  37. };
  38.  
  39. Indexer(T& t): _container(t) {}
  40.  
  41. iterator begin() const { return iterator(_container.begin()); }
  42. iterator end() const { return iterator(_container.end()); }
  43.  
  44. private:
  45. T& _container;
  46. }; // class Indexer
  47.  
  48. template <typename T>
  49. Indexer<T> index(T& t) { return Indexer<T>(t); }
  50.  
  51. int main() {
  52. std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9};
  53.  
  54. auto in = index(v);
  55.  
  56. for (auto it = in.begin(), end = in.end(); it != end; ++it) {
  57. auto p = *it;
  58. std::cout << p.first << ": " << p.second << "\n";
  59. }
  60. }
Success #stdin #stdout 0s 3016KB
stdin
Standard input is empty
stdout
0: 1
1: 2
2: 3
3: 4
4: 5
5: 6
6: 7
7: 8
8: 9