Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column iterators for a 2D array C++

I have a vector of floats, which I treat as a 2D array, declared as

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

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.

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. 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.

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?

like image 719
Timo Avatar asked Feb 25 '14 13:02

Timo


1 Answers

If you don't want to use boost, the easiset way to do it is to define your own iterator

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.

You'll have different implementations if you want to iterate on a single column or the whole array with column first.

like image 188
Kiwi Avatar answered Sep 30 '22 21:09

Kiwi