为矩阵设计一个简单的C ++迭代器 [英] Design a simple C++ iterator for Matrix

查看:94
本文介绍了为矩阵设计一个简单的C ++迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当时正在考虑使用 ++ 操作设计一个简单的C ++迭代器,对于诸如STL之类的向后和向前迭代,行为会有所不同。这样可以通过行和列访问矩阵 A

I was thinking to design a simple C++ iterator with ++ operation behave differently for backward and forward iterations like STL. So that a matrix A can be access through row and column as below,

  A.row(3).begin()
  A.row(3).end()
  A.col(3).begin()
  A.col(3).end()
  A.col(3).rbegin()
  A.col(3).rend()

  ++ A.row(3).begin()
  ++ A.col(3).rbegin()

我的矩阵类如下所示,

class Matrix {
 public:
  Iter row(size_t rowID);
  Iter col(size_t colID);
 private:
  vector<int> data_{1, 2, 3, 4, 5, 6};
  size_t nRow{3};
  size_t nCol{2};
};

是否有关于如何设计 Iter 类?

Is there any suggestions on how I can design my Iter class?

推荐答案

您可以简单地将步幅存储在迭代器内部,即指针将每个指针移动多远时间增加或减少。沿着一个轴的步幅为1,而在另一个轴上的步幅为矩阵的尺寸。

You can simply store the "stride" inside the iterator, that is how far the pointer moves each time it is incremented or decremented. Along one axis the stride is 1, while on the other it is the dimension of the matrix.

如果您的矩阵是这样的:

If your matrix is this:

1 2 3 4
6 7 8 9

然后row(0).begin()指向1和row(0).end()指向6(跨度为1),而column(2).begin()指向3和column(3).end()指向8以下的未使用单元格(步幅为4)。

Then row(0).begin() points to 1 and row(0).end() points to 6 (with stride of 1), while column(2).begin() points to 3 and column(3).end() points to an unused cell below 8 (with stride of 4).

boost :: make_strided_iterator()会为您完成此操作。

这篇关于为矩阵设计一个简单的C ++迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆