我有一个二维数组,我已经将其实现为std :: vector
的std :: vector
,如下所示:
struct Cell
{};
struct Column
{ std::vector<Cell*> m_column; };
struct Grid
{ std::vector<Column> m_grid; }
我想为Grid构建一个输入迭代器类,这样你就可以这样做...
for (const auto cell : grid)
cell->doSomething();
...并使用其他STL算法。但我不确定如何制作迭代器增量函数。
目前为止,我有以下内容:
struct Grid
{
std::vector<Column> m_grid;
struct ConstIterator
{
using value_type = const Cell*;
using reference = const Cell*&;
using pointer = const Cell**;
using difference_type = std::ptrdiff_t;
using iterator_category = std::input_iterator_tag;
reference operator* () { return curr; }
ConstIterator& operator++ () { incrementAcrossGrid(); return *this; }
ConstIterator operator++(int) { const auto temp(*this); incrementAcrossGrid(); return temp; }
bool operator== (const ConstIterator& that) { return curr == that.curr; }
bool operator!= (const ConstIterator& that) { return !(*this == that); }
void incrementAcrossGrid()
{
// ???
}
const Cell* curr;
};
ConstIterator begin() const { return { m_grid.front().m_column.front() }; }
ConstIterator end() const { return { m_grid.back().m_column.back() + 1 }; } // Is there a better way to get the end?
};
如您所见,我不确定在
incrementIterator()
里应该放什么。增加它直到达到列的末尾很容易,但我不知道如何将其从一列底部指向下一列顶部。也许我的方法完全错误,所以所有建议都受欢迎(包括Boost库等)。重要的是我需要能够使用Grid::begin()和Grid::end()来遍历单元格。
std::vector<Column>
,另一个用于遍历当前Column
中的std::vector<Cell*>
。 - Yksisarvinen