我有兩個結構:ARRAY2D(多維)和ARRAY(一維)。我想從類型ARRAY2D中獲得一列,並將其複製到ARRAY類型中。從C中的多維數組中獲取列的有效方法是什麼?
雖然我的代碼在下面工作,並且我認識到這可能是從數組中獲取列的一種很差的方式,但我很好奇可能存在哪些優化來避免O(n2)算法。從C中的數組中獲取列的有效方法是什麼?
BOOL arr2_getColumn(ARRAY2D *arr, const int column_index, ARRAY *returnedArray)
{
int x, y;
int i = 0;
/* Check for valid array. */
if (arr->blnIsInit != TRUE)
return FALSE;
/* Initialize array with the column's height. */
if (!arr_init(returnedArray, arr->height))
return FALSE;
/* Copy over column. */
for (y = 0; y < arr->height; y++)
{
for (x = 0; x <= column_index; x++)
{
if (x == column_index)
{
returnedArray->array[i] = arr->array[y * arr->width + x];
i++;
}
}
}
/* Set the new size. */
returnedArray->size = arr->height;
return TRUE;
}
的可能重複的[如何獲得在C/C++?多維數組的列(http://stackoverflow.com/questions/15258084/how-to-get-column-of-a-multidimensional -array-in-cc) –
不,不是我.... – Phil
另外,我們不知道ARRAY2d和ARRAY應該是什麼。 – Gandaro