简体   繁体   English

用于2D数组C ++的列迭代器

[英]Column iterators for a 2D array C++

I have a vector of floats, which I treat as a 2D array, declared as 我有一个浮动向量,我将其视为2D数组,声明为

std::vector<float> vec(height*width);

The numerical problem I'm working on requires processing both in rows and in columns, with identical algorithms, so I'd like to be able to write them via iterators and just input a row iterator or a column iterator, as appropriate. 我正在处理的数值问题需要在行和列中处理相同的算法,所以我希望能够通过迭代器编写它们,并且只需输入行迭代器或列迭代器。

To clarify, here's the pointer arithmetic version of access to the array: 为了澄清,这里是访问数组的指针算术版本:

valueatxy = vec[y*width + x];

The row iterator form is of course trivial, say I have an function template<class iter> void process(iter begin, iter end) , the call is 行迭代器形式当然是微不足道的,比方说我有一个函数template<class iter> void process(iter begin, iter end) ,调用是

process(vec.begin(), vec.end());

Now in order to be able to use the same function for a column operation, I need a column iterator. 现在为了能够使用相同的函数进行列操作,我需要一个列迭代器。 This is essentially the same iterator as the usual vector iterator, except that the increment operator, and all other pointer-arithmetic-like operators, increment by multiples of width. 这与通常的向量迭代器基本上是相同的迭代器,除了增量运算符和所有其他类似指针算术的运算符,以宽度的倍数递增。 The call should go something like 电话应该是这样的

process(columnit(vec.begin() + x, width),
columnit(vec.begin() + x + width, width));

Where columnit is the column iterator class, constructed to increment the underlying iterator by width steps. 其中columnit是列迭代器类,构造为通过宽度步长递增底层迭代器。

Now, my question is, what is the easiest way to define such a modified iterator? 现在,我的问题是,定义这样一个修改过的迭代器的最简单方法是什么? Defining a new iterator from scratch involves a lot of boilerplate, at least if I want it to be even remotely stl-compatible. 从头开始定义一个新的迭代器涉及很多样板,至少如果我希望它甚至是远程stl兼容的话。 The Boost iterator adaptor is designed to help with this, and it's clearly an option, but since I don't think I'll need Boost for anything else, this seems like a bit of an overkill. Boost迭代器适配器旨在帮助解决这个问题,而且它显然是一个选项,但由于我认为我不需要Boost做其他任何事情,这似乎有点矫枉过正。

Since the specific modification of the iterator I need is so trivial, I would imagine there would be an even simpler way, like maybe somebody has already made the kind of adaptor I need? 由于我需要的迭代器的具体修改是如此微不足道,我想会有一个更简单的方法,就像有人已经制作了我需要的那种适配器?

If you don't want to use boost , the easiset way to do it is to define your own iterator 如果你不想使用boost ,那么easyiset方法就是定义你自己的迭代器

struct col_iterator : public std::iterator<std::forward_iterator_tag, value_type>

And the body of the operator++ will increment your current index by the number of columns. 并且operator++的主体将按当前列数增加当前索引。

You'll have different implementations if you want to iterate on a single column or the whole array with column first. 如果要首先使用列迭代单个列或整个数组,则可以使用不同的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM