二维和三维阵列的等效迭代展平为一维阵列?

时间:2014-01-18 02:59:49

标签: c++ arrays

我有以下代码将2D维数组展平为1D C样式数组:

#include <iostream>

int main()
{
    int width = 4, height = 4;

    int arr[width * height];

    for (int i = 0, k = 0; i < height; ++i)
    {
        for (int j = 0; j < width; ++j)
        {
            arr[i * width + j] = k++;
        }
    }



    for (int i = 0; i < height; ++i)
    {
        for (int j = 0; j < width; ++j)
        {
            int* ptr = &arr[0] + height * i; //perfect also works with &arr[0] + width * i;
            std::cout<<ptr[j]<<"   ";
        }
    }
}

打印:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 如下所示:http://ideone.com/gcgocu 数组不必是正方形(4x4),上面仍然有效。

现在我正在尝试用3D数组做同样的事情,所以我做了:

#include <iostream>

int main()
{
    int width = 4, height = 4, depth = 4;

    int arr[width * height * depth];

    for (int i = 0, l = 0; i < depth; ++i)
    {
        for (int j = 0; j < height; ++j)
        {
            for (int k = 0; k < width; ++k)
            {
                arr[k + width * (j + depth * i)] = l++; //works just fine. perfect.
            }
        }
    }

    //Fails below.. Run-time access violation error.

    for (int i = 0; i < depth; ++i)
    {
        for (int j = 0; j < height; ++j)
        {
            for (int k = 0; k < width; ++k)
            {
                int** ptr = reinterpret_cast<int**>(&arr[0] + width * (j + depth * i)); //this can't be right.
                std::cout<<ptr[j][k]; //this line should stay the same.
            }
        }
    }

    return 0;
}

它失败,如此处所示:http://ideone.com/yqY2oK

如何为3D阵列做同样的事情?

2 个答案:

答案 0 :(得分:2)

以下内容应该有效:

for (int i = 0, l = 0; i < depth; ++i) {
    for (int j = 0; j < height; ++j) {
        for (int k = 0; k < width; ++k) {
            arr[k + width * (j + height * i)] = l++; // Index fixed
        }
    }
}

for (int i = 0; i < depth; ++i) {
    int (&ptr)[height][width] = *reinterpret_cast<int (*)[height][width]>(&arr[0] + width * height * i);
    for (int j = 0; j < height; ++j) {
        for (int k = 0; k < width; ++k) {
            std::cout << ptr[j][k] << " "; //this line should stay the same.
        }
    }
}

而在2D片段中:

int (&ptr)[width] = *reinterpret_cast<int (*)[width]>(&arr[0] + width * i);

答案 1 :(得分:0)

int** cast会获取你的1-d数组并使其成为指针数组。它不会将您的值映射到平面数组。

您可以使用boost::multi_array做您想做的事。