C++如何为向量向量构建迭代器

C++ how to build iterator for vector of vectors

本文关键字:向量 构建 迭代器 C++      更新时间:2023-10-16

我有一个二维数组,我已经实现了它作为std::vectors的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(( 来迭代 Cells。

基本思想是在自定义迭代器中保留两个迭代器:

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