Advertisement
mfgnik

Untitled

Mar 6th, 2023
714
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. template<class Iterator>
  2. class IteratorRange {
  3. public:
  4.     IteratorRange(Iterator begin, Iterator end) : begin_(begin), end_(end) {}
  5.  
  6.     Iterator begin() const {
  7.         return begin_;
  8.     }
  9.  
  10.     Iterator end() const {
  11.         return end_;
  12.     }
  13.  
  14. private:
  15.     Iterator begin_;
  16.     Iterator end_;
  17. };
  18.  
  19. template<class T>
  20. class RangeIterator {
  21. public:
  22.     RangeIterator(T current, T step) : current_(current), step_(step) {}
  23.  
  24.     RangeIterator& operator++() {
  25.         current_ += step_;
  26.         return *this;
  27.     }
  28.  
  29.     bool operator!=(const RangeIterator &other) const {
  30.         return current_ != other.current_;
  31.     }
  32.  
  33.     auto operator*() const {
  34.         return current_;
  35.     }
  36.  
  37. private:
  38.     T current_;
  39.     T step_;
  40. };
  41.  
  42.  
  43. template<class T>
  44. auto Range(T from, T to, T step) {
  45.     return IteratorRange(RangeIterator(from, step), RangeIterator(to, step));
  46. }
  47.  
  48.  
  49. template<class Iterator>
  50. class GroupIterator {
  51. public:
  52.     GroupIterator(Iterator current, Iterator end) : current_(current), end_(end) {}
  53.  
  54.     GroupIterator& operator++() {
  55.         auto old_value = *current_;
  56.         while (current_ < end_ && *current_ == old_value) {
  57.             ++current_;
  58.         }
  59.         return *this;
  60.     }
  61.  
  62.     bool operator!=(const GroupIterator& other) {
  63.         return current_ != other.current_;
  64.     }
  65.  
  66.     auto operator*() const {
  67.         return *current_;
  68.     }
  69.  
  70. private:
  71.     Iterator current_;
  72.     Iterator end_;
  73. };
  74.  
  75.  
  76. template <class Iterator>
  77. auto Group(Iterator begin, Iterator end) {
  78.     return IteratorRange(GroupIterator(begin, end), GroupIterator(end, end));
  79. }
  80.  
  81.  
  82. int main() {
  83.     for (auto value: Range(1, 5, 1)) {
  84.         std::cout << value << " ";
  85.     }
  86.     std::cout << "\n";
  87.    
  88.     std::vector<int> v{1, 1, 1, 2, 2, 3, 1, 1, 2, 2, 3};
  89.  
  90.     for (auto value : Group(v.begin(), v.end())) {
  91.         std::cout << value << " ";
  92.     }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement