[英]C++ : Creating 1-d array which contains the elements from 3-d array
I'm trying to create 1-dimensional array containing elements from 3-dimensional array 我正在尝试创建包含3维数组中的元素的1维数组
For example: 例如:
float array[4][3][6];
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 6; k++) {
temp[4] = {array[0][j][k],array[1][j][k],array[2][j][k],array[3][j][k]};
}
}
However when I compiled the code, it returned an error as follow for line 4: error: expected primary-expression before '{' token
and error: expected
;' 但是,当我编译代码时,它在第4行返回了以下错误:
error: expected primary-expression before '{' token
, error: expected
;' before '{' token` 在“ {”令牌之前
Does anyone know what went wrong here? 有人知道这里出了什么问题吗?
This method worked before, but I'm really stumped at what happening now. 这种方法以前曾奏效,但我真的对现在发生的事情感到困惑。
Thank you. 谢谢。
// create 1d array with 3d property's
float array[width * height * depth];
// get and set functions
float get(int x,int y,int z)
{
return array[x + (y * width)+ (z * width * height)];
}
void set(float value,int x,int y,int z)
{
array[x + (y * width)+ (z * width * height)] = value;
}
//iterate over the array
for(int z = 0; z < depth; ++z)
for(int y = 0; y < height; ++y)
for(int x = 0; x < width ; ++x)
get(x,y,z);
The {}
can only be use for initialization at compile time and need to be constant. {}
仅可在编译时用于初始化,并且需要保持不变。
You would need to use float temp[4];
您将需要使用
float temp[4];
and then in your loop: 然后在你的循环中:
temp[0] = array[0][j][k]
temp[1] = array[1][j][k]
temp[2] = array[2][j][k]
temp[3] = array[3][j][k]
This will make your code compile but you know that in the end, only 4 component of your 3-d array will remain and those will be 这将使您的代码得以编译,但您知道最后,3-d数组将仅保留4个组件,而这些组件将
array[0][2][5],array[1][2][5],array[2][2][5],array[3][2][5]
Unless you didn't show all the code, you might as well skip the 2 loops and just affect them directly. 除非没有显示所有代码,否则您最好跳过这两个循环并直接影响它们。
I think you can use something like this: 我认为您可以使用以下方式:
float array[4][3][6];
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 6; k++) {
for (int i=0; i < 4; i++ )
temp[i] = array[i][j][k];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.