c++ - 为非 STL 容器创建我自己的迭代器

标签 c++ stl iterator

我有一个管理数据的类。

我希望仅返回其中的部分数据,但由于这是一个需要多次完成的过程,因此我不希望仅将数据复制到容器内并返回容器。

如果我可以发送推荐信或类似的内容,那就太好了。我想到了迭代器。但因为我使用 Eigen3 Matrix (它没有迭代器(无论如何都是二维矩阵))

我正在考虑模拟(?)迭代器的行为, 像这样的东西:

typedef unsigned int Index;

class MatrixIterator
{
public:
    MatrixIterator(Eigen::MatrixXd *m, Index min, Index max):
        _col(0), _index(0), _min(min), _max(max), _matrix(m)
    {}

    void operator++ ()   
    {
        if (_index + _min + 1 != _max)
            _index++; 
    }
    void operator--()
    {
        if (_index != _min)
            _index--; 
    }

    double operator*()
    { 
        return _matrix->operator() (_index + _min, _col); 
    }

    void setCol(Index col)  {   _col = col; }

    Index min() {   return _min;    }
    Index max() {   return _max;    }

private:
    // the matrix is 2D we can select
    // on which column we want to iterate
    Index _col;

    // current position
    Index _index;

    // select the range on which the user can iterate
    Index _max;
    Index _min;

    // the matrix on which we want to iterate over
    Eigen::MatrixXd* _matrix;
}
  • 我以前从未真正使用过迭代器,对吗?
  • 我可以从 std::iterator 继承我的 MatrixIterator 以便 STL 能够将其理解为普通的迭代器吗?
  • 您知道做类似事情的更好方法吗?

我已阅读:

编辑:我只想迭代矩阵的一部分(这就是我有 _min 和 _max 的原因),我正在操作的数据是时间序列,因此数据已经排序。 我认为我们可以将 MatrixIterator 视为对数据查询的响应。

最佳答案

I never really used iterators before, is it correct ?

这是一个好的开始。这个想法是正确的,但你遗漏了一些东西。首先,你没有足够的运营商。请务必检查reference并提供您可以合理提供的每个运算符(唯一可能有用或可能没用的运算符是随机访问运算符,因为在这种情况下可能更难实现)。其次,您需要提供iterator traits为你的迭代器类。这通常是通过在迭代器类中创建必要的嵌套 typedef 来完成的(您也可以为您的类专门化 std::iterator_traits 模板,但我想说,只有当您确实无法添加嵌套类型定义)。

Can I inherit my MatrixIterator from std::iterator so stl would be able to understand it as a usual iterator ?

不,一般来说,您不应该继承 std::iterator 类。 STL 是一个模板库(通用编程(GP)),因此不像 OOP 那样使用基类继承模型。 STL 算法将迭代器作为模板参数,并且通常会根据算法的要求(或尽可能根据与迭代器类型关联的 iterator_category 特征)使用它们。这是generic programming ,不是面向对象编程,而是苹果和橘子。

Do you know a better way to do something similar ?

嗯,一种方便的方法是使用像 boost::iterator_facade 这样的类模板(参见 ref ),它提供了一种创建迭代器的自动“填空”机制。它使用众所周知且非常有用的Curiously Recurring Template Pattern (或简称 CRTP)。这很有用,因为实现迭代器所需的所有运算符可能非常冗长且重复,并且通常仅真正依赖于几个核心操作(这就是您在使用像 这样的 CRTP 类时需要“填写”的全部内容) boost::iterator_facade)。

关于c++ - 为非 STL 容器创建我自己的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22793127/

相关文章:

c++ - std::将数据移出 Eigen::Matrix

c++ - msgpack:将类打包到成员函数中

c++ - map 的内积

generics - 在 Rust 中编写一个将可迭代容器作为参数的通用函数

variables - int i 与 int index 等哪个更好?

c++ - 使用共享库编译可执行文件时,仅链接所需的符号

c++ - 我在理解 [basic.scope.pdecl]/7 时遇到一些困难

c++ - 为什么 push_back 或 push_front 使双端队列的迭代器无效?

c++ - 在 C++ 中处理 UTF-8

c++ - 在 C++ 映射上使用迭代器删除