我正在尝试使用多维BitArray,但我被如何用它设置或读取位所困扰。
使用普通的一维BitArray,我可以简单地执行以下操作来设置一点:
bitArray.Set(0, true);然而,我不知道如何对二维位数组做同样的事情。例如,下面的代码没有意义,因为Set方法需要一个索引,但我之前已经在"0,0“中提供了索引:
bitArray[0, 0].Set(0, true);我的问题:制作和使用多维BitArray的正确方法是什么
发布于 2014-05-18 10:11:18
就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];发布于 2019-09-29 05:20:42
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();
}
}
}https://stackoverflow.com/questions/23717880
复制相似问题