我有一个问题,我需要将两个输入映射到一个输出。
我知道字典是一般类型的线性映射:
for every x (
key
) there may be a y (value
)
我需要的是多维映射:
for every x,y (
key
) there may be a z (value
)
当然,更重要的是我需要它来支持通用类型和动态调整大小。
此数据结构是否存在于 C# 中,还是我必须创建字典的字典?如果没有必要,我宁愿不重新发明轮子。
重新发明轮子:
using System;
using System.Collections.Generic;
using System.Text;
namespace zlib.Collections
{
public class Dictionary3D<Tx, Ty, Tz>
{
private Dictionary<Tuple<Tx, Ty>, Tz> _dict = new Dictionary<Tuple<Tx, Ty>, Tz>();
public void Add(Tx x, Ty y, Tz z)
{
_dict.Add(Tuple.Create<Tx, Ty>(x, y), z);
}
public void Clear()
{
_dict.Clear();
}
public bool ContainsKey(Tx x, Ty y)
{
return _dict.ContainsKey(Tuple.Create<Tx, Ty>(x, y));
}
public bool ContainsValue(Tz z)
{
return _dict.ContainsValue(z);
}
public Dictionary<Tuple<Tx, Ty>, Tz>.Enumerator GetEnumerator()
{
return _dict.GetEnumerator();
}
public bool Remove(Tx x, Ty y)
{
return _dict.Remove(Tuple.Create<Tx, Ty>(x, y));
}
public bool TryGetValue(Tx x, Ty y, out Tz z)
{
return _dict.TryGetValue(Tuple.Create<Tx, Ty>(x, y), out z);
}
public int Count
{
get { return _dict.Count; }
}
public Dictionary<Tuple<Tx,Ty>,Tz>.KeyCollection Keys
{
get
{
return _dict.Keys;
}
}
public Dictionary<Tuple<Tx, Ty>, Tz>.ValueCollection Values
{
get
{
return _dict.Values;
}
}
public Tz this[Tx x, Ty y]
{
get
{
return _dict[Tuple.Create<Tx, Ty>(x, y)];
}
set
{
_dict[Tuple.Create<Tx, Ty>(x, y)] = value;
}
}
}
}
似乎重新发明轮子在回应中胜出。这是我到目前为止想出的代码,但我觉得应该有更好的方法,比如 matrix
或其他东西。
最佳答案
关于
Dictionary<Tuple<T,K>,Tuple<L,J>>
??
关于c# - 我应该使用什么数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7855678/