我有一个二维数组,我已将其实现为 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() 来迭代单元格。
最佳答案
基本思想是在自定义迭代器中保留两个迭代器:
struct Iterator {
reference operator* () {
return *cell_iterator;
}
Iterator& operator++() {
if (++cell_iterator == col_iterator->m_column.end()) {
++col_iterator;
cell_iterator = col_iterator->m_column.begin();
}
return *this;
}
bool operator==(const Iterator& that) const {
return col_iterator == that.col_iterator &&
cell_iterator == that.cell_iterator;
}
std::vector<Cell*>::iterator cell_iterator;
std::vector<Column>::iterator col_iterator;
};
auto Grid::begin() -> Iterator {
return Iterator{m_grid.begin()->m_column.begin(), m_grid.begin()};
}
这只是一个想法。您应该考虑如何正确表示 Grid::end()
迭代器并对 operator++()
进行必要的更改。当 col_iterator
命中 m_grid.end()
时,您无法再取消引用它来获取下一个 cell_iterator
。
关于C++ 如何为 vector 的 vector 构建迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59016448/