Search code examples
c++c#-4.0jagged-arrays

jagged arrays of multiple types


i'm not really sure if it is possible but can a jagged array contain multiple types

i need a data structure layered of which the first 2D layer is of the type bytes Then the next 2D layers can be integer type or float type and finally 2D layer will be again byte, the total number of layers can vary.

is that possible if yes, how would i declare it in C# and how in c++ ?


Solution

  • An approach in C# could be one of the following:

    // Base class for each layer
    abstract class Layer
    {
        public abstract int Rank { get; }
        public abstract int GetLength(int dimension);
    }
    
    // Individual layers would inherit from the base class and handle
    // the actual input/output
    class ByteLayer : Layer
    {
        private byte[,] bytes;
    
        public override int Rank { get { return 2; } }
    
        public override int GetLength(int dimension)
        {
            return this.bytes.GetLength(dimension);
        }
    
        public ByteLayer(byte[,] bytes)
        {
            this.bytes = bytes;
        }
    
        // You would then expose this.bytes as you choose
    }
    // Also make IntLayer and FloatLayer
    

    You could then create an abstraction to hold each of these layer types:

    class Layers : IEnumerable<Layer>
    {
        private ByteLayer top, bottom;
        private List<Layer> layers = new List<Layer>();
    
        public ByteLayer Top { get { return top; } }
        public IEnumerable<Layer> Middle { get { return this.layers.AsEnumerable(); } }
        public ByteLayer Bottom { get { return bottom; } }
    
        public Layers(byte[,] top, byte[,] bottom)
        {
            this.top = top;
            this.bottom = bottom;
        }
    
        public void Add(int[,] layer)
        {
            this.layers.Add(new IntLayer(layer));
        }
    
        public void Add(float[,] layer)
        {
            this.layers.Add(new FloatLayer(layer));
        }
    
        public IEnumerator<Layer> GetEnumerator()
        {
            yield return bottom;
            foreach (var layer in this.layers) yield return layer;
            yield return top;
        }
    }