Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11: Efficiently iterating over matrix with single range-loop?

Tags:

c++

gcc

c++11

(For a concrete compiler/platform context take GCC 4.7 and Ubuntu 12.04 on x86_64)

Given some function f:

void f(int x, int y);

int nx = ...;
int ny = ...;

One way to iterate over every value (x,y) from (0,0) to (nx,ny) is:

for (int x = 0; x < nx; x++)
    for (int y = 0; y < ny; y++)
        f(x,y);

Let this compile to some generated code Q1.

We will write a function g such that:

for (auto it : g(Z))
    f(it.x, it.y);

compiles to code Q2.

Is it possible to write g such that Q2 is as efficient as Q1? If yes, how? If not, what is the closest we can get?

You may change auto to auto& or auto&& if it helps.

You may also change it.x to it.x(), and it.y to it.y(), if it helps.

(Recall that the expansion of range-based for is just an iterator-like type of your choosing: C++11: The range-based for statement: "range-init" lifetime?)

like image 683
Andrew Tomazos Avatar asked May 31 '12 02:05

Andrew Tomazos


1 Answers

Is it possible to write g such that Q2 is as efficient as Q1? If yes, how? If not, what is the closest we can get?

Sure its possible, you just need to define iterators that increment in the same way as your for loop. From the top of my head:

class matrix_iterator
{
public:
    ...

    matrix_iterator& operator++()
    {
        if( ++y >= ny )
        {
            ++x;
            y = 0;
        }

        return *this;
    }

private:
    int nx, ny;
    int x, y;
};
like image 121
K-ballo Avatar answered Sep 21 '22 21:09

K-ballo