将一维二维数组分配给一维矩阵

时间:2012-07-12 19:00:59

标签: c++ gaussian

所以我有一个2D数组,我想将2D数组的第'pth'行分配给一个新的1D数组: 我的代码如下所示:

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的所有值 aMatrix的行,但它只包含一个值。我已尝试过该声明的所有组合但是 除了编译错误之外别无其他。

我的问题是进行此项任务的正确方法是什么?

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

2 个答案:

答案 0 :(得分: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]; 
}

答案 1 :(得分:0)

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

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

std::array<Row, 10> aMatrix;

Row temp = aMatrix[5];
相关问题