# [c++] 创建我自己的迭代器

/编辑：我看到，自己的迭代器实际上在这里是必要的（我误解了第一个问题）。 不过，我将下面的代码放在了代码中，因为它在类似的情况下很有用。

``````// Your class `Piece`
class Piece {
private:
Shape m_shape;

public:

typedef std::vector<Point>::iterator iterator;
typedef std::vector<Point>::const_iterator const_iterator;

iterator begin() { return m_shape.container.begin(); }

const_iterator begin() const { return m_shape.container.begin(); }

iterator end() { return m_shape.container.end(); }

const_iterator end() const { return m_shape.const_container.end(); }
}
``````

Question

``````#include <iostream>
#include <vector>

#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<Point> 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);
};
``````

``````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;
}
``````