fork download
  1.  
  2.  
  3. #include <iostream>
  4. #include <vector>
  5. #include <tuple>
  6. #include <functional>
  7.  
  8. template<typename C>
  9. struct indexed_container
  10. {
  11. struct indexed_iterator
  12. {
  13. typedef typename C::value_type value_type;
  14. typedef std::tuple<size_t, std::reference_wrapper<value_type>> tuple_type;
  15.  
  16. typename C::iterator _it;
  17. size_t _index;
  18.  
  19. indexed_iterator(typename C::iterator it) : _it(it), _index(0) {}
  20.  
  21. indexed_iterator& operator++()
  22. {
  23. ++_it;
  24. ++_index;
  25. return *this;
  26. }
  27. bool operator == (indexed_iterator const & other)
  28. {
  29. return _it == other._it;
  30. }
  31. bool operator != (indexed_iterator const & other)
  32. {
  33. return _it != other._it;
  34. }
  35. tuple_type operator*()
  36. {
  37. return std::make_tuple(_index, std::ref(*_it));
  38. }
  39. };
  40.  
  41. indexed_container(C & c) : _c(c) {}
  42.  
  43. indexed_iterator begin()
  44. {
  45. return indexed_iterator(_c.begin());
  46. }
  47. indexed_iterator end()
  48. {
  49. return indexed_iterator(_c.end());
  50. }
  51. private:
  52. C & _c;
  53. };
  54.  
  55. template<typename C>
  56. auto make_indexable(C & c) -> indexed_container<C>
  57. {
  58. return indexed_container<C>(c);
  59. }
  60.  
  61. int main()
  62. {
  63. std::vector<int> v{1,2,3};
  64. for(auto item : make_indexable(v))
  65. {
  66. std::cout << std::get<0>(item) << " => " << std::get<1>(item) << std::endl;
  67.  
  68. std::get<1>(item) *= 10; //modify value
  69. }
  70. std::cout << "\nModified\n";
  71. for(auto item : make_indexable(v))
  72. {
  73. std::cout << std::get<0>(item) << " => " << std::get<1>(item) << std::endl;
  74. }
  75. }
  76.  
Success #stdin #stdout 0s 2984KB
stdin
Standard input is empty
stdout
0 => 1
1 => 2
2 => 3

Modified
0 => 10
1 => 20
2 => 30