C++ 如何为 vector 的 vector 构建迭代器

标签 c++ iterator

我有一个二维数组,我已将其实现为 std::vectorstd::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/

相关文章:

c++ - Cmake:为多配置 cmake 项目指定配置特定设置

c++ - mapvalue和迭代器c++的比较

python - 将生成器转换为迭代器类的最佳方法

c++ - 有没有办法为 std::map 中小于给定键的第一个元素找到反向迭代器?

c++ - 图中的角点和边缘检测

C++链接器设计问题

c++ - C++ 中的二进制搜索 : Ascending + Descending Ordered Arrays

c++ - pthread_create 没有参数?

algorithm - 给定整数迭代器的正迭代器设计

c++ - 迭代器中的代理对象