fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <iterator>
  4.  
  5. class MyIterator : public std::iterator<std::random_access_iterator_tag, double>
  6. {
  7. public:
  8. MyIterator() : container(nullptr), i(0), j(0) {}
  9.  
  10. MyIterator(const std::vector<std::vector<double>>& container,
  11. std::size_t i,
  12. std::size_t j) : container(&container), i(i), j(j)
  13. {
  14. // Skip empty container
  15. if (i < container.size() && container[i].empty())
  16. {
  17. j = 0;
  18. ++(*this);
  19. }
  20. }
  21. MyIterator(const MyIterator& rhs) = default;
  22. MyIterator& operator = (const MyIterator& rhs) = default;
  23.  
  24. MyIterator& operator ++() {
  25. if (++j >= (*container)[i].size()) {
  26. do {++i;} while (i < (*container).size() && (*container)[i].empty());
  27. j = 0;
  28. }
  29. return *this;
  30. }
  31. MyIterator operator ++(int) { auto it = *this; ++(*this); return it; }
  32.  
  33. MyIterator& operator --() {
  34. if (j-- == 0) {
  35. do { --i; } while (i != 0 && (*container)[i].empty());
  36. j = (*container)[i].size();
  37. }
  38. return *this;
  39. }
  40. MyIterator operator --(int) { auto it = *this; --(*this); return it; }
  41.  
  42. double operator *() const { return (*container)[i][j]; }
  43.  
  44.  
  45. bool operator == (const MyIterator& rhs) const {
  46. return container == rhs.container && i == rhs.i && j == rhs.j;
  47. }
  48. bool operator != (const MyIterator& rhs) const { return !(*this == rhs); }
  49.  
  50. private:
  51. const std::vector<std::vector<double>>* container;
  52. std::size_t i;
  53. std::size_t j;
  54. };
  55.  
  56. MyIterator MyIteratorBegin(const std::vector<std::vector<double>>& container)
  57. {
  58. return MyIterator(container, 0, 0);
  59. }
  60.  
  61. MyIterator MyIteratorEnd(const std::vector<std::vector<double>>& container)
  62. {
  63. return MyIterator(container, container.size(), 0);
  64. }
  65.  
  66. int main() {
  67. std::vector<std::vector<double>> values = {{5,0,8}, {}, {3,1,9}};
  68.  
  69. auto b = MyIteratorBegin(values);
  70. auto e = MyIteratorEnd(values);
  71. auto p = std::minmax_element(b, e);
  72.  
  73. if (p.first != e) {
  74. std::cout << "min is " << *p.first << " and max is " << *p.second << std::endl;
  75. }
  76.  
  77. }
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
min is 0 and max is 9