gpt4 book ai didi

c++ - 扁平化为 1D 数组的 2D 和 3D 数组的等效迭代?

转载 作者:行者123 更新时间:2023-11-30 04:09:29 25 4
gpt4 key购买 nike

我有以下代码,用于将二维数组展平为一维 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 阵列做同样的事情?

最佳答案

以下应该有效:

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

而在二维片段中:

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

关于c++ - 扁平化为 1D 数组的 2D 和 3D 数组的等效迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21199467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com