【问题标题】:Why would I use a HashSet over a Dictionary?为什么我要在字典上使用 HashSet?
【发布时间】:2015-03-16 12:55:12
【问题描述】:

我正在尝试在 A* 算法上实现缓存路径列表。目前,缓存的路径存储在这样的列表中:

readonly List<CachedPath> _cachedPaths = new List<CachedPath>();

对这个列表执行的操作是:

FirstOrDefault 获取满足一定条件的元素

var cached = _cachedPaths.FirstOrDefault(p => p.From == from && p.To == target && p.Actor == self);

删除和元素

_cachedPaths.Remove(cached);

补充

_cachedPaths.Add(new CachedPath {
                    From = from,
                    To = target,
                    Actor = self,
                    Result = pb,
                    Tick = _world.WorldTick
                });

注意:类 CachedPath 的 GetHashCode 和 Equals 仅被 From、To 和 Actor 覆盖,因此具有这些相同属性的两个实例具有相同的哈希和相等性。

鉴于“HashSet”中的快速查找(包含)、插入和删除是 O(1)(如果我没记错的话),我考虑使用“HashSet”来执行这些操作。唯一的问题是 FirstOrDefault,我必须枚举整个集合才能得到它。

鉴于这个问题,我还考虑使用由 From、To 和 Actor 的哈希索引的 Dictionary:

Dictionary<int, CachedPath> cachedPath

再一次,如果我没记错的话,Dictionary 还提供了 O(1) 的插入、删除和 Key 检索。这让我认为 Dictionary 是一种 HashSet + O(1) 元素检索功能。

我错过了什么吗?从支持更多操作的意义上说,Dictionary 真的比 HashSet 更好吗?

提前致谢。

【问题讨论】:

标签: c# dictionary hashset


【解决方案1】:

Dictionary 并不比HashSet更好,只是不同而已。

  • 当您想要存储无序的项目集合时,您可以使用 HashSet,并且
  • 当您想要将一组称为“键”的项与另一组称为“值”的项相关联时,您可以使用 Dictionary

可以将HashSet 视为没有关联值的Dictionary(实际上,HashSet 有时在幕后使用Dictionary 实现),但没有必要在此考虑它方式:将两者视为完全不同的事情也可以。

在您的情况下,您可以通过按演员制作字典来提高性能,如下所示:

Dictionary<ActorType,List<CachedPath>> _cachedPathsByActor

这样你的线性搜索会根据演员快速选择一个子列表,然后按目标线性搜索:

var cached = _cachedPathsByActor[self].FirstOrDefault(p => p.From == from && p.To == target);

或通过创建一个考虑所有三个项目的相等比较器,并使用 DictionaryCachedPath 作为键和值,并将自定义 IEqualityComparer&lt;T&gt; 作为键比较器:

class CachedPathEqualityComparer : IEqualityComparer<CachedPath> {
    public bool Equals(CachedPath a, CachedPath b) {
        return a.Actor == b.Actor
            && a.From == b.From
            && a.To == b.To;
    }
    public int GetHashCode(CachedPath p) {
        return 31*31*p.Actor.GetHashCode()+31*p.From.GetHashCode()+p.To.GetHashCode();
    }
}
...
var _cachedPaths = new Dictionary<CachedPath,CachedPath>(new CachedPathEqualityComparer());
...
CachedPath cached;
if (_cachedPaths.TryGetValue(self, out cached)) {
    ...
}

但是,这种方法假定字典中最多有一个项目具有相同的 FromToActor

【讨论】:

  • 那么对于这种情况,使用 Actor.GetHashcode() + From.GetHashCode() + To.GetHashCode() 作为键而不是仅仅使用 Actor 怎么样?不是更快吗?
【解决方案2】:

哈希集在执行添加时不会抛出异常。相反,它返回一个反映添加成功的布尔值。

哈希集也不需要 keyValue 对。 我使用哈希集来保证唯一值的集合。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-06
    • 2011-06-09
    • 2013-03-21
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    相关资源
    最近更新 更多