以 3 步迭代一维数组(伪二维):
arr = new int[height * width * 3];
for (int i = 0; i < height * width * 3; i+=3) {
arr[i] = 1;
}
我已经试过了,但我得到的是三分之一的列:
for (int y = 0; y < height * 3; y++) {
for (int x = 0; x < width; x+=3) {
arr[x + width * y] = 1;
}
}
最佳答案
假设您的单元格的“大小”为 3 个条目,您应该在内循环中使用 * 3
。否则你会错过每行三分之二的单元格。
您还需要将 width
乘以 3 以获得正确的行。
for (int y = 0; y < height; y++) {
for (int x = 0; x < width * 3; x+=3) {
arr[x + width * 3 * y] = 1;
}
}
一般情况下,您需要以下结构来应对这种情况:
for (int y = 0; y < height; y++) {
for (int x = 0; x < width * cellWidth; x+= cellWidth) {
arr[x + width * cellWidth * y] = 1;
}
}
(在您的情况下 cellWidth
是 3)
为了稍微简化这一点,您可以在循环中假设您的单元格的宽度为 1(就像正常情况一样),并在实际分配值时乘以 cellWidth
:
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int index = (x + width * y) * cellWidth;
arr[index + 0] = 1; // First 'cell entry'
arr[index + 1] = 1; // Second
...
arr[index + cellWidth - 1] = 1; // Last
}
}
另一种解决方案是使用 struct
创建更大的“项目”,例如:
typedef struct { int r, int g, int b } t_rgb;
t_rgb* arr = new t_rgb[height * width];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
arr[x + width * y].r = 1;
}
}
并且您可以将其用作常规数组(编译器会为您进行所有计算)。这也使您的代码中发生的事情更加清晰。
关于c++ - 使用 step 遍历一维数组和二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22657707/