2011-10-14 36 views
0

我創建了一個多維數組,並且想要將整個內部數組設置爲等於單獨的(單個維度)數組。我怎麼能這樣做,除了通過陣列中的每個位置並設置grid[row][val] = inputNums[val]在C中的多維數組中設置內部數組#

int[,] grid = new int[20,20]; 

// read a row of space-deliminated integers, split it into its components 
// then add it to my grid 
string rowInput = ""; 
for (int row = 0; (rowInput = problemInput.ReadLine()) != null; row++) { 
    int[] inputNums = Array.ConvertAll(rowInput.Split(' '), (value) => Convert.ToInt32(value)) 
    grid.SetValue(inputNums , row); // THIS LINE DOESN'T WORK 
} 

我發現了特定的錯誤是:

「Arguement異常來處理:陣列不是一維陣列」

回答

5

您正在將具有多維數組的「鋸齒狀」數組(數組陣列)混合使用。你想用什麼可能是交錯數組(因爲沒有人在他的腦子會想使用MD陣列:-))

int[][] grid = new int[20][]; 

// ... 
grid[row] = inputNums; 

// access it with 
grid[row][col] = ... 

// columns of a row: 
var cols = grid[row].Length; 

// number of rows: 
var rows = grid.Length; 

一個MD陣列是一個單一的monolithical「對象」與許多細胞。數組的數組取代了許多對象:對於2d鋸齒形數組,一個對象用於行「結構」(外部容器),一個用於每個「行」。因此,最後鋸齒陣列,您必須做一個new int[20, 20],與一個鋸齒陣列,你必須做一個new int[20][],將創建20行和20 myArray[x] = new int[20](與x = 0 ... 19)每行一個。啊......我忘記了:鋸齒狀的數組可以是「鋸齒狀的」:每個「行」可以有不同數量的「列」。 (即使對於3D和* d陣列,我所告訴你的所有內容都是有效的:-)你只需要將其縮放即可)