C ++ 11: Is iterating over a single range matrix efficient?

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

For some function f:

void f(int x, int y);

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

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

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

Let this compile with some generated Q1 code.

We will write a function g such that:

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

compiled Q2 code.

Can g be written so that Q2 is as efficient as Q1? If so, how? If not, then the closer we can get?

You can change auto to auto & or auto && if that helps.

You can also change it.x to it.x () and it.y to it.y () if that helps.

(, , : ++ 11: : " range- init " ?)

+5
2

g , Q2 , Q1? , ? , ?

, , , , for. :

class matrix_iterator
{
public:
    ...

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

        return *this;
    }

private:
    int nx, ny;
    int x, y;
};
+3

. , , ( ) .

struct iter {
    int x, y, ny;
    iter(int x, int y, int ny) : x(x), y(y), ny(ny) {}
    iter &operator++ () {
        if (++y >= ny)
        {
            y = 0;
            ++x;
        }
        return *this;
    }
    bool operator != (iter const &rhs) const {
        return y != rhs.y || x != rhs.x;
    }
};

struct container {
    iter endit;
    container(int nx, int ny) : endit(nx, ny, ny) {}
    iter begin() const { return iter(0,0,endit.ny); }
    iter const &end() const { return endit; }
};

container g(Z const &z) { return container(z.nx, z.ny); }

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

All Articles