嵌套循环 - 一维索引
Nested for loop - 1D indexing
//The size of test doesn't matter for now just assume it's fitting
int* test = new int[50000]
for(int i=stepSize;i<=maxValue;i+=stepSize){
for(int j=0;j<=i;j+=stepSize){
//Comput something and store it
test[i*30+j] = myfunc();
}
}
如果我现在想将其转换为一维数组,如何计算一维数组的正确索引?例如,对于 i=5 和 j=0,它应该在第一次 posistion 等处。
编辑:更新了代码。我试图计算一些东西并通过使用 i*30+j 计算其索引将其存储在 1d 数组中,但这不起作用。
假设数组定义如下:
int a[30][5];
您可以像这样索引它:
a[i][j]
或者将其定义为一维数组,如下所示:
int a[30*5];
a[j + 5*i];
下面是一个显示迭代的示例程序:
(请注意,有些人可能会说我切换了行和列,但这并不重要,因为它在数组中连续迭代。也就是说,如果您以不同的方式考虑行和列,只需切换所有出现次数,您应该会得到相同的结果。
int main(int argc, char **argv)
{
int columns = 30;
int rows = 5;
int a[columns*rows]; // not really needed for this example
for(int i = 0; i < columns; ++i)
{
for(int j = 0; j < rows; ++j)
{
cout << "[" << i << "][" << j << "] offset: " << (i*rows + j)
<< endl;
}
}
}
[0][0] offset: 0
[0][1] offset: 1
[0][2] offset: 2
[0][3] offset: 3
[0][4] offset: 4
[1][0] offset: 5
[1][1] offset: 6
[1][2] offset: 7
[1][3] offset: 8
[1][4] offset: 9
[2][0] offset: 10
[2][1] offset: 11
[2][2] offset: 12
[2][3] offset: 13
[2][4] offset: 14
[3][0] offset: 15
[3][1] offset: 16
[3][2] offset: 17
[3][3] offset: 18
...
[27][4] offset: 139
[28][0] offset: 140
[28][1] offset: 141
[28][2] offset: 142
[28][3] offset: 143
[28][4] offset: 144
[29][0] offset: 145
[29][1] offset: 146
[29][2] offset: 147
[29][3] offset: 148
[29][4] offset: 149
还有一条信息,如果您需要动态分配 2D 数组,方法如下:
int **a = new int*[30];
for(int i = 0; i < 30; ++i)
{
a[i] = new int[5];
}
相关文章:
- 如何将三维尺寸不固定的三维阵列展平为一维阵列
- STL算法函数在多个一维容器上的使用
- 将二维数组的所有元素插入到一维数组中
- C++语法差异:二维和一维数组(指针算术)
- 将一维数组写入 CSV C++中的不同列?
- C++:将矩阵存储在一维数组中
- 当表示为对象的一维向量时,有效地旋转 NxM 矩阵 (C++)
- 如何在一维数组中的每个元素中都有多个int值
- 以C++填充一维数组
- 一维阵列的运动检测(神经网络或其他选项?
- 编写所需的代码以创建动态一维整数数组
- 用于在一维数组上嵌套循环操作的正确 openmp 指令
- 使用两个不同大小的一维阵列制作 2D 阵列
- 将一维数组的索引转换为二维数组
- 使用double-for循环索引一维数组
- array:将一维数组的索引转换为多维数组的向量索引
- 嵌套循环 - 一维索引
- 将一维"flattened"索引转换为 N 维数组的 N 维向量索引
- 我应该总是用一个有自己索引的一维向量,还是一个多维向量
- 如何将矩阵的索引映射到一维数组(c++)