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

Lia*_*cre 3 c++ iterator

我有我已经实现为一个二维阵列std::vectorstd::vectorS,如下所示:

struct Cell
{};

struct Column
{ std::vector<Cell*> m_column; };

struct Grid
{ std::vector<Column> m_grid; }
Run Code Online (Sandbox Code Playgroud)

我想为Grid构建一个输入迭代器类,以便您可以执行此操作...

for (const auto cell : grid)
    cell->doSomething();
Run Code Online (Sandbox Code Playgroud)

...并使用其他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?
};
Run Code Online (Sandbox Code Playgroud)

如您所见,我不确定要放什么incrementIterator()。很容易将其递增,直到到达其列的末尾,但是我不知道如何将其从一列的底部指向下一列的顶部。

可能是我采用了完全错误的方法,因此欢迎所有建议(包括Boost库等)。重要的是,我需要能够使用Grid :: begin()和Grid :: end()遍历单元格。

Evg*_*Evg 8

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

struct Iterator {
    reference operator* () { 
        return *cell_iterator;
    }

    Iterator& operator++() {
        if (cell_iterator != col_iterator->m_column.end())
            ++cell_iterator;
        else {
            ++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()};
}
Run Code Online (Sandbox Code Playgroud)

这只是一个想法。您应该考虑如何Grid::end()正确表示迭代器并对进行必要的更改operator++()。当col_iterator点击时m_grid.end(),您不能再取消引用它以获取下一个cell_iterator