甲SDK被返回我具有多個尺寸的陣列,例如:如何在不知道傳遞給您的數組的維數和元素的情況下迭代多維數組?
int[,,] theArray = new int[2,8,12];
我需要每個元素訪問數組中並返回值和所述值的位置。我需要做到這一點不知道在傳遞尺寸和數組的元素個數
for循環甲SDK被返回我具有多個尺寸的陣列,例如:如何在不知道傳遞給您的數組的維數和元素的情況下迭代多維數組?
int[,,] theArray = new int[2,8,12];
我需要每個元素訪問數組中並返回值和所述值的位置。我需要做到這一點不知道在傳遞尺寸和數組的元素個數
for循環會這樣的工作嗎?它遞歸隊列,以便您可以使用foreach()並獲取包含當前項目索引的數組。
class Program
{
static void Main(string[] args)
{
int[, ,] theArray = new int[2, 8, 12];
theArray[0, 0, 1] = 99;
theArray[0, 1, 0] = 199;
theArray[1, 0, 0] = 299;
Walker w = new Walker(theArray);
foreach (int i in w)
{
Console.WriteLine("Item[{0},{1},{2}] = {3}", w.Pos[0], w.Pos[1], w.Pos[2], i);
}
Console.ReadKey();
}
public class Walker : IEnumerable<int>
{
public Array Data { get; private set; }
public int[] Pos { get; private set; }
public Walker(Array array)
{
this.Data = array;
this.Pos = new int[array.Rank];
}
public IEnumerator<int> GetEnumerator()
{
return this.RecurseRank(0);
}
private IEnumerator<int> RecurseRank(int rank)
{
for (int i = this.Data.GetLowerBound(rank); i <= this.Data.GetUpperBound(rank); ++i)
{
this.Pos.SetValue(i, rank);
if (rank < this.Pos.Length - 1)
{
IEnumerator<int> e = this.RecurseRank(rank + 1);
while (e.MoveNext())
{
yield return e.Current;
}
}
else
{
yield return (int)this.Data.GetValue(this.Pos);
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.RecurseRank(0);
}
}
}
非常好的例子,效果很好。 – 2009-10-30 08:57:00
用途:
for (int i=theArray.GetLowerBound(0);i<=theArray.GetUpperBound(0);++i)
{
for (int j=theArray.GetLowerBound(1);j<=theArray.GetUpperBound(1);++j)
{
for (int k=theArray.GetLowerBound(2);k<=theArray.GetUpperBound(2);++k)
{
// do work, using index theArray[i,j,k]
}
}
}
如果你不知道的尺寸提前數,你可以使用Array.Rank來確定。
感謝您的回答。我的問題是,在它傳遞給我之前,我不知道數組的等級或界限。任何其他建議將非常感激。 – 2009-10-27 00:07:07
您可以使用theArray.Rank獲得排名,並且邊界由我上面的代碼自動確定。 – 2009-10-27 00:16:37
我不知道我理解你的問題有關「返回的位置[N,N,N]」,但如果你想從一個方法返回多個值,有有幾種方法可以做到這一點。
•使用out
或參考參數(例如,Int
)在返回該方法之前設置爲返回值。
•傳入一個數組,例如一個三個整數的數組,其中的元素在返回之前由方法設置。
•返回值的數組,例如一個三個整數的數組。
這是一個家庭作業? – zvolkov 2009-10-27 01:25:32