等效于允许重复键的排序字典 [英] equivalent to a sorted dictionary that allows duplicate keys

查看:46
本文介绍了等效于允许重复键的排序字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个数据结构,该结构可以按与它们关联的浮点键对对象进行排序,从最低开始.麻烦的是,键代表成本,所以经常有重复项,我不在乎这一点,因为如果两个键具有相同的成本,那么我会抓住第一个,因为这没有什么区别,问题在于编译器会抱怨./p>

是否存在一种行为相同但允许重复键的数据结构?

编辑-尽管我仍然需要重复,因为如果结果证明是一个死胡同,我会抓住下一个(它们是a *搜索中的节点)

因此,为了清楚起见,它需要允许按顺序排序的重复键.

解决方案

您编写:

等同于允许重复键的字典

我需要一个数据结构,该结构可以按与它们关联的浮点键对对象进行排序,从最低到最低.

字典不会按键对项目进行排序,因此您要查找的结构实际上根本不等同于 Dictionary .您想要的与 SortedList SortedDictionary 类似,不同之处在于它应该允许重复的键.

.NET中不存在此类.但是,您有一些选择:

  • 即使您通常通常只需要第一个,如果您想存储与某个键相关的所有值,请使用 SortedDictionary< double,List< TValue>> .首次插入密钥时,请创建一个新列表并将该值添加到列表中.插入已经存在的密钥时,获取列表并将值附加到列表中.
  • 您的编辑意味着该方法不适用于您的情况. 使用 SortedDictionary< double,TValue> 并检查插入前重复.仅会存储每个键的第一个值,因此与上述方法不同,此方法根本无法访问第二个值.
  • 找到一个第三方收藏库,该图书馆的类可以满足您的需求.

相关

I need a data structure that can sort objects by the float keys they're associated with, lowest first. The trouble is that the keys represent cost so there are often duplicates, I don't care about this because if two have the same cost I'll just grab the first as it makes no difference, the problem is that the compiler complains.

Is there a data structure that behaves in the same way but allows duplicate keys?

EDIT - I still need the duplicates though because if one turns out to be a dead-end, I grab the next (they're nodes in an a* search)

so just to be clear, it needs to allow duplicate keys that are sorted in order.

解决方案

You write:

equivalent to a dictionary that allows duplicate keys

I need a data structure that can sort objects by the float keys they're associated with, lowest first.

A dictionary does not keep the items sorted by the keys, so the structure you are looking for is actually not equivalent to a Dictionary at all. What you want is something similar to a SortedList or SortedDictionary except that it should allow duplicate keys.

No such class exists in .NET. However you have a few options:

  • Use SortedDictionary<double, List<TValue>> if you want to store all the values associated for a key, even though you usually only need the first. When inserting a key for the first time, create a new list and add the value to the list. When inserting a key that already exists, fetch the list and append the value to the list.
  • Your edit means that this approach does not apply to your situation. Use SortedDictionary<double, TValue> and check for duplicates before inserting. Only the first value for each key will be stored, so unlike the above approach, you can't access the second value at all with this method.
  • Find a third party collections library that has a class that does what you want.

Related

这篇关于等效于允许重复键的排序字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆