如何为我的Matrix类创建一个迭代器 [英] How to make an iterator for my Matrix class

查看:68
本文介绍了如何为我的Matrix类创建一个迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作矩阵类,这是我的代码:

Hi, i''m making a matrix class, here is my code:

展开 | 选择 | Wrap | 行号

推荐答案

矩阵中的数据不是连续的,即您不将其分配为单个数据块,而是分配指针数组,然后分配给每个指针以分配值类型的数组。


这意味着当你处于一行数据的末尾时,你无法保证(实际上不太可能)下一行的开头是在下一行的开头记忆位置。

你有几个选择
The data in your matrix is not contiguous, that is you do not allocate it as a single block of data but rather you allocate an array of pointers and then to each pointer to allocate an array of the value types.

That means that when you are at the end of a row of data you have no guarantee (and in fact it is very unlikely) that the start of the next row is in the next memory location.

You have a couple of options
  1. 你的迭代器++运算符需要更复杂。当运算符运行时,它需要检测它是否在当前行的末尾,并且明确地开始使用下一行。
  2. 您的数据结构需要不那么复杂。您可以将其简单地实现为一个单一维度的值类型数组,而不是指向值类型数组的指针数组。您可以使用行和列为任何给定单元格计算此数组中的正确索引。直接单元访问稍微复杂一些,但数据管理和迭代器的复杂性都降低了。


非常感谢您的回答,遗憾的是我无法使用第二个选项因为老师要求我们不要以这种方式实现矩阵

我已经尝试了第一个选项,但是我无法使其工作...因为我需要比较我的用_data [row] [_ col-1]指针,然后如果它们是相同跳到_data [row + 1] [0],否则我只会递增我的指针

问题是我不明白我怎么能在我的类迭代器中使用我的类矩阵的_data,以便我可以将它与我的指针进行比较...我可以通过迭代器的构造函数中的引用传递它吗?它会起作用吗? br />

ps:再次,抱歉我的英文,谢谢你的帮助!
thanks a lot for your answer, unfortunately i cannot use the second option cause the teacher asked us to not implement the matrix in that way
I have already tried the first option, but i wasn''t able to make it works...cause i would need to compare my pointer with _data[row][_col-1], then if they are the same skip to _data[row+1][0], else i would just increment my pointer
The problem is that i dont understand how can i make _data of an istance of my class matrix available in my class iterator, so that i can compare it to my pointer...can i pass it by reference in the constructor of the iterator?would it work?

ps:again, sorry for my english and thanks for your help!



我是不明白我怎么能做出_data的信息我的类矩阵在我的类迭代器中可用,所以我可以将它与我的指针进行比较...我可以传递它吗
that i dont understand how can i make _data of an istance of my class matrix available in my class iterator, so that i can compare it to my pointer...can i pass it



只需查看C ++向量标题并查看如何在标准库中实现迭代器。你会发现一个类的迭代器本身是一个嵌套在它迭代的类中的类。

Just look in the C++ vector header and see how iterators are implemented in the Standard Library. You will find the iterator for a class is itself a class nested inside the class it iterates.

展开 | 选择 | Wrap | 行号


这篇关于如何为我的Matrix类创建一个迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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