在C++中编写自定义迭代器可能会非常冗长和复杂难懂。
由于我找不到一种最简单的编写自定义迭代器的方式,因此我编写了
this template header,可以提供帮助。例如,要使
Piece
类可迭代:
#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 equal(const it_state& s) const { return pos == s.pos; }
};
SETUP_ITERATORS(Piece, Point, it_state);
};
然后你就可以将其用作普通的STL容器:
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;
}
return 0;
}
它还允许添加其他类型的迭代器,如
const_iterator
或
reverse_const_iterator
。
我希望这有所帮助。