【问题标题】:C# - Multidimensional BitArrayC# - 多维位数组
【发布时间】:2014-07-06 05:46:36
【问题描述】:

我正在尝试使用多维 BitArray,但我不知道如何使用它设置或读取位。

使用普通的一维 BitArray 我可以简单地执行以下设置:

bitArray.Set(0, true);

但是我不知道如何对二维位数组做同样的事情。例如下面的代码没有意义,因为Set 方法需要一个索引,但我之前已经在“[0, 0]”中提供了索引:

    bitArray[0, 0].Set(0, true);

我的问题:制作并使用多维BitArray 的正确方法是什么?

【问题讨论】:

  • 您不需要BitArray 实例的二维数组,因为BitArray 已经包含一维数组。只需使用BitArray[] 进行二维存储。
  • 你能详细说明一下吗?

标签: c# arrays multidimensional-array bitarray


【解决方案1】:

CLR 而言,BitArray 的实例不是数组(也就是说,BitArray 不是“数组类型”)。如果您想存储 2 维位信息,您有几个选择(我的所有示例都创建 10x20 2D 体积):

a) 像这样使用BitArray 的单个数组:

// Init:
BitArray[] storage = new BitArray[ 20 ];
for(int y=0;y<storage.Length;y++) storage[y] = new BitArray( 10, true );

// Usage:
Boolean at5x7 = storage[7][5];

b) 通过按行列索引,将 BitArray 本身用作 2D 空间(这实际上会更快,因为 CLR 不会经常调用其​​边界检查):

// Init:
const Int32 width = 10, height = 20;
BitArray storage = new BitArray( width * height );

// Usage:
Boolean at5x7 = storage[ (5 * width) + 7];

【讨论】:

    【解决方案2】:
    public sealed class BitArray2D
    {
        private BitArray _array;
        private int _dimension1;
        private int _dimension2;
    
        public BitArray2D(int dimension1, int dimension2)
        {
            _dimension1 = dimension1 > 0 ? dimension1 : throw new ArgumentOutOfRangeException(nameof(dimension1), dimension1, string.Empty);
            _dimension2 = dimension2 > 0 ? dimension2 : throw new ArgumentOutOfRangeException(nameof(dimension2), dimension2, string.Empty);
            _array = new BitArray(dimension1 * dimension2);
        }
    
        public bool Get(int x, int y) { CheckBounds(x, y); return _array[y * _dimension1 + x]; }
        public bool Set(int x, int y, bool val) { CheckBounds(x, y); return _array[y * _dimension1 + x] = val; }
        public bool this[int x, int y] { get { return Get(x, y); } set { Set(x, y, value); } }
    
        private void CheckBounds(int x, int y)
        {
            if (x < 0 || x >= _dimension1)
            {
                throw new IndexOutOfRangeException();
            }
            if (y < 0 || y >= _dimension2)
            {
                throw new IndexOutOfRangeException();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-27
      • 1970-01-01
      • 2010-10-18
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多