배열의 치수와 요소의 수와 요소의 수를 알지 못하고 다중 정문 배열을 어떻게 반복합니까?
-
06-07-2019 - |
문제
SDK는 다음과 같은 여러 차원의 배열을 반환합니다.
int[,,] theArray = new int[2,8,12];
배열의 각 요소를 방문하고 값의 값과 위치를 반환해야합니다. 배열의 치수와 요소의 수를 모르면이 작업을 수행해야합니다.
해결책
이런 일이 당신을 위해 일할까요? 순위를 재발하여 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);
}
}
}
다른 팁
루프 사용 :
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]
}
}
}
치수 수를 미리 모르는 경우 사용할 수 있습니다. 배열 그것을 결정하기 위해.
나는 당신의 질문에 대한 당신의 질문을 이해하지 못한다 "위치를 반환 [n, n, n], 그러나 방법에서 둘 이상의 값을 반환하려고한다면 몇 가지 방법이 있습니다.
• 사용out
또는 기준 매개 변수 (예 :Int
) 메소드에서 돌아 오기 전에 반환 된 값으로 설정됩니다.
• 배열, 예를 들어, 3 개의 int 배열로 전달되며 요소는 반환하기 전에 메소드에 의해 설정됩니다.
• 값 배열 (예 : 세 개의 int 배열)을 반환합니다.
제휴하지 않습니다 StackOverflow