C++如何为向量向量构建迭代器
C++ how to build iterator for vector of vectors
我有一个二维数组,我已经实现了它作为std::vector
s的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
。
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 如何在提升间进程中构建具有给定计数的向量并向其添加元素
- 如何在目录及其子文件夹中构建文件名字符串向量?
- 创建一个类来访问和指定向量类型,并构建一个获取位置并为其分配区域的类
- C++如何为向量向量构建迭代器
- 使用步骤c++构建一个向量
- 在编译时以增量方式构建变量指针的向量
- 如何通过向量构建数组
- 如何通过参考构建向量的子句法
- 如何使用由for循环创建的向量向量构建链接列表
- 如何使用向量字符串令牌构建表达树
- 如何从 2 个向量构建顶点矩阵?
- 如何使用opencv从矩阵向量中构建图像
- glm ::翻译 - 它是否从向量构建矩阵
- 使用PETSC库与向量构建稀疏矩阵
- Cgal::D ynamic_dimension_tag 在尝试构建点向量时出错
- 如何使用C++构建可以旋转的向量数组
- 包含从 mysql row[x] 构建的固定长度数组的向量
- 基于另一个向量构建的向量的成员的geting索引
- 如何从源向量构建搜索结果的向量<><>?