2012-07-12 146 views
0

所以我有一个二维数组,我想将二维数组的行“第p”行分配给一个新的一维数组: 我的代码如下所示:将二维数组的一行分配到一维矩阵

float temp[] = { *aMatrix[p] }; // aMatrix is a 10x10 array 
           // am trying to assign the pth row 
           // to temp. 

*aMatrix[p] = *aMatrix[max]; 

*aMatrix[max] = *temp; 

float t = bMatrix[p]; 
bMatrix[p] = bMatrix[max]; 

在上面的声明之后,temp应该是长度为10的矩阵的第pth 行的所有值,但它只包含一个值。我已经尝试过所有的组合,但 只能编译错误..

我的问题是做这个任务的正确方法是什么?

任何帮助,将不胜感激。 谢谢

+0

'* aMatrix [p]'给你一个'float' - 你提取两次。这使得'temp'为1个浮点数组。 – jrok 2012-07-12 19:22:56

回答

3

它看起来像你有点混淆指针。您无法使用简单的作业复制所有成员。 C++不支持成员数组的赋值。你应该通过像这样的元素:

float temp[10]; 

// copy the pth row elements into temp array. 
for(int i=0; i<10; i++) { 

    temp[i] = aMatrix[p][i]; 
} 

你也可以做到这一点,如果你的aMatrix可能可能在某个时候改变长度第二种方式:

int aLength = sizeof(aMatrix[p])/sizeof(float); 

float temp[aLength]; 

// copy the pth row elements into temp array. 
for(int i=0; i < aLength; i++) { 

    temp[i] = aMatrix[p][i]; 
} 
+0

谢谢我刚刚开始考虑同样的事情,但希望有更好的方法来做到这一点。 – 2012-07-12 19:24:13

0

为什么不使用std::array?与C风格的数组不同,它是可赋值的。

typedef std::array<float, 10> Row; 

std::array<Row, 10> aMatrix; 

Row temp = aMatrix[5]; 
+0

谢谢。在这个任务中,所有这些工作都需要做一些重大更改才能实现。 – 2012-07-12 19:42:39