2012-07-12 134 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

相關問題