使用字典实现自己的功能相当简单。下面的实现适用于2个维度,但您可以轻松实现3或4个维度。当矩阵稀疏时,存储非常有效。如果您计划频繁添加或删除列,那么这不是一个好的实现。
class SparseMatrix<T>
{
public T this[int i, int j]
{
get
{
T result;
if (!_data.TryGetValue(new Key(i, j), out result))
return default(T);
return result;
}
set { _data[new Key(i, j)] = value; } // Could remove values if value == default(T)
}
private struct Key
{
public Key(int i, int j)
{
_i = i;
_j = j;
}
private readonly int _i;
private readonly int _j;
public override bool Equals(object obj)
{
if (!(obj is Key))
return false;
var k = (Key) obj;
return k._i == _i && k._j == _j;
}
public override int GetHashCode()
{
return _i << 16 + _j; // Could be smarter based on the distribution of i and j
}
}
private readonly Dictionary<Key, T> _data = new Dictionary<Key, T>();
}