2010-06-29 52 views
1

我正在写一些我自己的数据结构,比如二叉树和四叉树以及kD树。是否有可能以允许任何维度的方式编写它们?是否可以实现通用维数据结构?

喜欢的东西:

KDTree<2, string> twoDTree = new KDTree<2, string>(); 
twoDTree[3,4] = "X,Y = (3,4)"; 

KDTree<4, string> fourDTree = new KDTree<4, string>(); 
fourDTree[0,1,2,3] = "x1,x2,x3,x4 = (0,1,2,3)"; 

我现在已经是明确创建每个维度,因为它是自己的类唯一的解决办法:

TwoDTree<string> twoDTree = new TwoDTree<string>(); 
twoDTree[3,4] = "X,Y = (3,4)"; 

FourDTree<string> fourDTree = new FourDTree<string>(); 
fourDTree[0,1,2,3] = "x1,x2,x3,x4 = (0,1,2,3)"; 

但这种复制粘贴一吨的代码,这应该能够以某种方式重用。

回答

1

不是真的,但我看到更多的选项:

传尺寸到构造和使用索引这样的:

public string this[params int[] indexes] { 
    get { 
    // return the data fr the index 
    } 
} 

这已经不是“安全类型”在编译时的缺点(如传入的尺寸将不会被检查出来)。

或者创建了一堆的界面和使用Reflection.Emit的创建,其在运行时实现正确的接口实例:

public interface IMultiDimensional<T> { 
    int Dimensions { 
    get; 
    } 

    int Rank(int dimension); 
} 

public interface I1Dimensional<T>: IMultiDimensional<T> { 
    T this[int index] { 
    get; 
    set; 
    } 
} 

public interface I2Dimensional<T>: IMultiDimensional<T> { 
    T this[int index1, int index2] { 
    get; 
    set; 
    } 
} 

public interface I3Dimensional<T>: IMultiDimensional<T> { 
    T this[int index1, int index2, int index3] { 
    get; 
    set; 
    } 
} 

public interface I4Dimensional<T>: IMultiDimensional<T> { 
    T this[int index1, int index2, int index3, int index4] { 
    get; 
    set; 
    } 
} 

public static TDimensional CreateMulti<TDimensional, TType>() where T: IMultiDimensional<TType> { 
    // emit a class with Reflection.Emit here that implements the interface 
} 

I4Dimensional<string> four = CreateMulti<I4Dimensional<string>, string>(); 
four[1,2,3,4] = "abc"; 
0

您可以使用多维数组作为通用参数,像这样:

KDTree<string[,,,]> 

但是,您将无法编写通用代码索引到多维数组,不能暴露给调用者:您可以考虑使用jagged arrays而不是多维数组。然后,您可以创建一个定义的数据的类型泛型类,并在构造函数中指定多少维度使用:

public class KDTree<T> { 
    private readonly T[][] m_Data; 

    public KDTree(int rows, int columns) { 
     m_Data = new T[rows][]; 
     for(int r = 0; r < rows; r++) 
     m_Data[r] = new T[columns]; 
    } 
} 
相关问题