C++ 嵌套for循环-1D索引 //现在测试的大小无关紧要,只要假设它合适就行了 整数*测试=新整数[50000] 对于(int i=步长;i
假设数组定义如下:C++ 嵌套for循环-1D索引 //现在测试的大小无关紧要,只要假设它合适就行了 整数*测试=新整数[50000] 对于(int i=步长;i,c++,2d,C++,2d,假设数组定义如下: //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 s
//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();
}
}
a[i][j]
您可以这样索引到它:
int a[30][5];
或将其定义为一维数组,如下所示:
//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();
}
}
a[i][j]
以下是显示迭代的示例程序:
(请注意,有些人可能会说我切换了行和列,但这并不重要,因为它在数组中连续迭代。也就是说,如果您对行和列的看法不同,只需切换所有出现的行和列,就会得到相同的结果。)
int main(int argc,char**argv)
{
int列=30;
int行=5;
int a[columns*rows];//本例中不需要
对于(int i=0;i 你试过什么了吗?另外,我觉得给出的代码示例毫无意义。它根本没有帮助。我更新了示例。基本上我想在嵌套的for循环中计算一些值,然后将结果存储在从0到n的1D数组中。为什么你在5开始迭代I
?你是如何声明数组的?基本上for循环是dynamic所以我从某个值开始,以步长(更新代码)的方式将它增加到某个最大值,好吧,但是你说的2D数组在哪里?乘法中的I
是错误的-你想要一行(或一列)中的元素数,取决于顺序)相反,这不起作用,因为计算出的索引i+i*j将是5、12、24等。但我希望它将值连续存储在位置0、1、2等上。即使使用j+5*i,它也不会给我连续的值indexing@user1356695,抱歉耽搁了,我刚吃过午饭回来,我用更多信息更新了答案。
int **a = new int*[30];
for(int i = 0; i < 30; ++i)
{
a[i] = new int[5];
}