您的數據以行優先順序列出。在讀取整型數組並驗證其內容後(即dim = 4意味着32個值跟隨,dim = 2意味着8個值跟隨,等等)。我不確定爲什麼要分配或循環任何東西。
I.e. 您可以使用物理測試[]的數據作爲矩陣:
如果是這樣,那麼請注意在上面的mat1
和mat2
的聲明中使用'dim')。它是C++的少數幾個特性之一,就像C++沒有的特性一樣。所以跟你帶的那個跳舞吧。
最後,假設你的編譯器是C99兼容,支持沃拉斯(__STDC_NO_VLA__
沒有被定義),作爲額外的超級特別分紅,是所有,但保證是最快的算法,讓您的兩個矩陣,因爲沒有算法。您讀取一個數組元素,然後分配兩個指針。 O(3)很難被擊敗。
例
#include <stdlib.h>
#include <stdio.h>
// main loader.
int main(int argc, char *argv[])
{
int test[] = {2,1,2,3,4,5,6,7,8};
int dim = test[0];
int (*mat1)[dim] = (int (*)[dim])(test+1);
int (*mat2)[dim] = (int (*)[dim])(test+1 + dim*dim);
// proof stuff is where it should be.
int i=0,j=0;
for (i=0;i<dim;i++)
{
for (j=0;j<dim;printf("%d ", mat1[i][j++]));
printf (" ");
for (j=0;j<dim;printf("%d ", mat2[i][j++]));
printf("\n");
}
return EXIT_SUCCESS;
}
輸出
1 2 5 6
3 4 7 8
類似的測試用的3×3的數據集:
int test[] = {3,1,2,3,4,5,6,7,8,9,9,8,7,6,5,4,3,2,1};
輸出
1 2 3 9 8 7
4 5 6 6 5 4
7 8 9 3 2 1
最後,設定一個4x4的數據:
int test[] = {4,1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,8,7,6,5,4,3,2,1,8,7,6,5,4,3,2,1};
輸出
1 2 3 4 8 7 6 5
5 6 7 8 4 3 2 1
1 2 3 4 8 7 6 5
5 6 7 8 4 3 2 1
你要找的關鍵詞是模和整數除法:) – Wolph
方陣? – yeyo
是的,他們是方矩陣。 – Unknown