清理方式写多个'for'循环 [英] Clean ways to write multiple 'for' loops

查看:93
本文介绍了清理方式写多个'for'循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于具有多个维度的数组,我们通常需要为其每个维度写入 for 循环。例如:

For an array with multiple dimensions, we usually need to write a for loop for each of its dimensions. For example:

vector< vector< vector<int> > > A;

for (int k=0; k<A.size(); k++)
{
    for (int i=0; i<A[k].size(); i++)
    {
        for (int j=0; j<A[k][i].size(); j++)
        {
            do_something_on_A(A[k][i][j]);
        }
    }
}

double B[10][8][5];
for (int k=0; k<10; k++)
{
    for (int i=0; i<8; i++)
    {
        for (int j=0; j<5; j++)
        {
            do_something_on_B(B[k][i][j]);
        }
    }
}

code> for-for-for 循环。我如何使用宏来定义 for-for-for 循环,这样我不需要每次都重写这种代码?有没有更好的方法来做这个?

You see this kind of for-for-for loops in our code frequently. How do I use macros to define the for-for-for loops so that I don't need to re-write this kind of code every time? Is there a better way to do this?

推荐答案

第一件事是你不使用这样的数据结构。如果
你需要一个三维矩阵,你定义一个:

The first thing is that you don't use such a data structure. If you need a three dimensional matrix, you define one:

class Matrix3D
{
    int x;
    int y;
    int z;
    std::vector<int> myData;
public:
    //  ...
    int& operator()( int i, int j, int k )
    {
        return myData[ ((i * y) + j) * z + k ];
    }
};

或者如果要使用 [] [] [] code>,您需要一个运算符[]
返回代理。

Or if you want to index using [][][], you need an operator[] which returns a proxy.

你这样做,如果你发现你不断地需要
迭代,你提出,你公开一个迭代器,
支持它:

Once you've done this, if you find that you constantly have to iterate as you've presented, you expose an iterator which will support it:

class Matrix3D
{
    //  as above...
    typedef std::vector<int>::iterator iterator;
    iterator begin() { return myData.begin(); }
    iterator end()   { return myData.end();   }
};

然后您只需输入:

for ( Matrix3D::iterator iter = m.begin(); iter != m.end(); ++ iter ) {
    //  ...
}

(或只是:

for ( auto& elem: m ) {
}

如果你有C ++ 11)。

if you have C++11.)

如果你在这样的迭代中需要三个索引,那么
就可能创建一个迭代器来暴露它们: / p>

And if you need the three indexes during such iterations, it's possible to create an iterator which exposes them:

class Matrix3D
{
    //  ...
    class iterator : private std::vector<int>::iterator
    {
        Matrix3D const* owner;
    public:
        iterator( Matrix3D const* owner,
                  std::vector<int>::iterator iter )
            : std::vector<int>::iterator( iter )
            , owner( owner )
        {
        }
        using std::vector<int>::iterator::operator++;
        //  and so on for all of the iterator operations...
        int i() const
        {
            ((*this) -  owner->myData.begin()) / (owner->y * owner->z);
        }
        //  ...
    };
};

这篇关于清理方式写多个'for'循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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