[英]How can I create a bool 3D array of char, int, int in C#
我正在嘗試創建一個包含char,int和int的bool 3d數組,例如
Table['a', 0, 5] = false;
Table['b', 1, 4] = true;
我創建了2d,但無法創建3d
var cells = new bool[word.Length, word.Length];
for (int i = 0; i < word.Length; i++)
{
for (int j = 0; j < word.Length; j++)
{
cells[i, j] = false; // what to write here
}
}
您可以使用元組和布爾的字典,如下所示:
var t = new Dictionary<Tuple<char, int, int>, bool>();
t.Add(Tuple.Create<char, int, int>('a', 0, 5), false);
t.Add(Tuple.Create<char, int, int>('b', 1, 4), true);
// Prints false
Console.WriteLine("a, 0, 5 = {0}", t[Tuple.Create<char, int, int>('a', 0, 5)]);
// Prints true
Console.WriteLine("b, 1, 4 = {0}", t[Tuple.Create<char, int, int>('b', 1, 4)]);
如果您堅持使用3D陣列 ,我建議這樣:
// ['a'..'z', 0..word.Length - 1, 0..word.Length - 1] bool array
// (first index is not zero-based)
bool[,,]cells = (bool[,,]) Array.CreateInstance(
typeof(bool), // Array items type
new int[] { 26, word.Length, word.Length }, // Sizes
new int[] { 'a', 0, 0 }); // Lower bounds
...
// Single item addressing
cells['b', 1, 4] = true;
...
// Loop over all the array's items
for (int i = cells.GetLowerBound(0); i <= cells.GetUpperBound(0); ++i)
for (int j = cells.GetLowerBound(1); j <= cells.GetUpperBound(1); ++j)
for (int k = cells.GetLowerBound(2); k <= cells.GetUpperBound(2); ++k) {
// ... cells[i, j, k] ...
}
看來您想從'a'
而不是從0
開始第一個索引,這就是為什么我提供了該復雜調用的原因。 請注意,您不必將數組的項目初始化為false
。
看到
https://msdn.microsoft.com/zh-CN/library/x836773a(v=vs.110).aspx
詳情
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.