gpt4 book ai didi

c# - 为什么我要使用 HashSet 而不是 Dictionary?

转载 作者:可可西里 更新时间:2023-11-01 08:54:02 25 4
gpt4 key购买 nike

我正在尝试在 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 类具有仅由 From、To 和 Actor 覆盖的 GetHashCode 和 Equals,因此具有这些相同属性的两个实例具有相同的哈希值和相等性。

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

考虑到这个问题,我考虑过使用由 From、To 和 Actor 的哈希值索引的字典:

Dictionary<int, CachedPath> cachedPath

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

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

提前致谢。

最佳答案

Dictionary不比HashSet更好 , 只是不同罢了。

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

人们可以想到 HashSet作为 Dictionary没有关联值(事实上,HashSet 有时在幕后使用 Dictionary 实现)但没有必要以这种方式考虑:将两者视为完全不同的事物也可以。

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

Dictionary<ActorType,List<CachedPath>> _cachedPathsByActor

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

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

或者通过制作一个考虑所有三个项目的相等比较器,并使用 DictionaryCachedPath作为键和值,以及自定义 IEqualityComparer<T> 作为关键比较器:

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)) {
...
}

但是,这种方法假定字典中至多有一项具有相同的 From。 , To , 和 Actor .

关于c# - 为什么我要使用 HashSet 而不是 Dictionary?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28009040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com