我正在编写一个类来将三维数组保持为一维。
我的代码中有一个错误:当数组1x1(xz)的大小为空时,所有写入元素。
告诉我错误在哪里,并告诉我已有哪些图书馆?
public class Arr3D<T> {
private T[] arr;
private Vector3 min, max;
private Vector3 size;
public Arr3D()
{
arr = new T[0];
}
public void AddOrReplace(T obj, Vector3 pos)
{
Vector3 newMin = Vector3.Min(min, pos); // ( Min(x1,x2), Min(y1,y2), ...
Vector3 newMax = Vector3.Max(max, pos+Vector3.one); // +(1,1,1)
if(newMin != min || newMax != max)
{
Resize(newMin, newMax);
}
Set(obj, pos);
}
public void Set(T obj, Vector3 pos)
{
Set(obj, pos.x, pos.y, pos.z);
}
public void Set(T obj, int x, int y, int z)
{
arr[ (y-min.y)*size.x*size.y + (z-min.z)*size.x + (x-min.x) ] = obj;
}
private void Resize(Vector3 newMin, Vector3 newMax)
{
Vector3 oldMin = min;
Vector3 oldMax = max;
T[] oldList = arr;
Vector3 oldSize = size;
min = newMin;
max = newMax;
size = newMax - newMin;
arr = new T[size.z*size.y*size.x];
for(int x=oldMin.x; x<oldMax.x; x++)
{
for(int y=oldMin.y; y<oldMax.y; y++)
{
for(int z=oldMin.z; z<oldMax.z; z++)
{
T val = oldList[(y-oldMin.y)*oldSize.x*oldSize.y + (z-oldMin.z)*oldSize.x + (x-oldMin.x)];
Set(val, x, y, z);
}
}
}
}
public T Get(int x, int y, int z)
{
return arr[(y-min.y)*size.x*size.y + (z-min.z)*size.x + (x-min.x)];
}
}
答案 0 :(得分:1)
在调整大小方法而不是
T[] oldList = arr;
您应该复制 arr (ay)的值,否则您将保留对 arr 的引用
T[] oldList ;
Array.Copy(arr,oldList,arr.Length) ;
有关详细信息,请参阅Array.Copy方法