在C#中,多维数组的概念非常酷。但我不明白什么时候使用它们。比如说,在哪种类型的应用程序中会使用这个概念。
不想听起来陈词滥调,但当你有多维数据时,你需要使用多维数组。
矩阵是一个常见的例子,但它也可以很容易地成为游戏棋盘(例如国际象棋),或者作为N维迷宫或计数器的数据模型,或者其他任何东西。
其中一个常见的用途是矩阵。
int[][] jagged = new int[5][];
for (int i=0; i<jagged.Length; i++)
{
jagged[i] = new int[10]; // length can be different for each sub-array, if needed
}
int[,] mArray = new int[5,10];
假设你想编写一个国际象棋游戏,你会如何使用一维数组来表示棋盘?
/**
* Reads the file into a char[rows][cols] matrix.
* @param String filename - the name of the file to read
* @return a two-dimensional array of chars containing file contents.
*/
private static char[][] readMatrix(String filename) throws IOException {
BufferedReader input = null;
try {
input = new BufferedReader(new FileReader(filename));
List<String> lines = new ArrayList<String>();
String line = null;
while ( (line = input.readLine()) != null ) {
lines.add(line);
}
int rows = lines.size();
char[][] matrix = new char[rows][];
for (int i=0; i<rows; i++) {
matrix[i] = lines.get(i).toCharArray();
}
return matrix;
} finally {
if(input!=null)input.close();
}
}
编辑:我应该说一下为什么我使用了一个矩阵...特别是因为我必须构建一个列表来获取数组...嗯?为什么不直接使用列表呢?简短的答案是速度。
访问一个数组(无论有多少维)在底层实现上是作为“索引算术”(又称指针算术)实现的,因此它不仅访问一个数组元素O(1),而且速度很快,是O(1)...比等效的arrayList.get(int index)(当你这样做几百万次时)要快得多...在(虽然是人工制造的)算法竞赛的世界中,速度就是一切。
谢谢。Keith。
Pixel[1024][768]
数组中的一个块。所以要找出屏幕左上角的像素是什么颜色,您需要查看Pixel[0][0]
。_Open = new char[][]
{ // 2 3 4 5 6 7 8 9 T J Q K A
new char [] {'P', 'F', 'F', 'F', 'F','F','F','F','F','F','F','P','P'}, // 2
new char [] {'F', 'P', 'F', 'F', 'F','F','F','F','F','F','F','P','P'}, // 3
new char [] {'F', 'F', 'P', 'F', 'F','F','F','F','F','F','F','P','P'}, // 4
new char [] {'F', 'F', 'F', 'P', 'F','F','F','F','F','F','F','P','P'}, // 5
new char [] {'F', 'F', 'F', 'F', 'P','F','F','F','F','F','F','P','P'}, // 6
new char [] {'F', 'F', 'F', 'F', 'F','P','F','F','P','F','F','P','P'}, // 7
new char [] {'F', 'F', 'F', 'F', 'F','F','P','P','P','P','F','P','P'}, // 8
new char [] {'F', 'F', 'F', 'F', 'F','F','F','P','P','P','P','P','P'}, // 9
new char [] {'F', 'F', 'F', 'F', 'F','F','F','F','P','P','P','P','P'}, // T
new char [] {'F', 'F', 'F', 'F', 'F','F','F','F','F','P','P','P','P'}, // J
new char [] {'F', 'F', 'F', 'F', 'F','F','F','P','P','P','P','P','P'}, // Q
new char [] {'P', 'P', 'P', 'P', 'P','P','P','P','P','P','P','P','P'}, // K
new char [] {'P', 'P', 'P', 'P', 'P','P','P','P','P','P','P','P','P'} // A
};
使用0代表2,12代表Ace。因此,如果模拟器检测到Ace,King,则会检查_Open [12] [11],看到'P'(表示'push'或'all-in'),并相应地采取行动。
虽然我相信其他人可以提供许多不同的例子,但我与机器人一起工作,机器人执行的许多任务之一是托盘装载,将物品按行和列的形式放在托盘上。 托盘上的每个位置都是数组的2个甚至3个维度索引的集合。
locationArrayt [row,column]
我们还将它们用于多语言应用程序。 字符串数组代表不同的错误消息,第二个索引是语言。
message [errorNumber,language]