Creating my own Iterators

前端 未结 6 1704
鱼传尺愫
鱼传尺愫 2020-11-29 15:58

I\'m trying to learn C++ so forgive me if this question demonstrates a lack of basic knowledge, you see, the fact is, I have a lack of basic knowledge.

I want some h

6条回答
  •  死守一世寂寞
    2020-11-29 16:20

    Writing custom iterators in C++ can be quite verbose and complex to understand.

    Since I could not find a minimal way to write a custom iterator I wrote this template header that might help. For example, to make the Piece class iterable:

    #include 
    #include 
    
    #include "iterator_tpl.h"
    
    struct Point {
      int x;
      int y;
      Point() {}
      Point(int x, int y) : x(x), y(y) {}
      Point operator+(Point other) const {
        other.x += x;
        other.y += y;
        return other;
      }
    };
    
    struct Shape {
      std::vector vec;
    };
    
    struct Piece {
      Shape& shape;
      Point offset;
      Piece(Shape& shape, int x, int y) : shape(shape), offset(x,y) {}
    
      struct it_state {
        int pos;
        inline void next(const Piece* ref) { ++pos; }
        inline void begin(const Piece* ref) { pos = 0; }
        inline void end(const Piece* ref) { pos = ref->shape.vec.size(); }
        inline Point get(Piece* ref) { return ref->offset + ref->shape.vec[pos]; }
        inline bool cmp(const it_state& s) const { return pos != s.pos; }
      };
      SETUP_ITERATORS(Piece, Point, it_state);
    };
    

    Then you would be able to use it as a normal STL Container:

    int main() {
      Shape shape;
      shape.vec.emplace_back(1,2);
      shape.vec.emplace_back(2,3);
      shape.vec.emplace_back(3,4);
    
      Piece piece(shape, 1, 1);
    
      for (Point p : piece) {
        std::cout << p.x << " " << p.y << std::endl;
        // Output:
        // 2 3
        // 3 4
        // 4 5
      }
    
      return 0;
    }
    

    It also allows for adding other types of iterators like const_iterator or reverse_const_iterator.

    I hope it helps.

提交回复
热议问题