按键自动排序对象的数据结构

本文关键字:对象 数据结构 排序 | 更新日期: 2023-09-27 18:36:27

我想要一个结构来根据关联的键自动为我排序数据,但是一旦完成此操作,我就不必用键抓取任何对象,我只想从列表中删除第一个。在我的特定情况下,每个对象都有一个关联的浮点值,我想从低到高对它们进行排序。

例如,我希望能够对整数列表进行排序,但通过它们相应的浮点"键"并抓取索引 0 处的那个 - (这将是具有最低相关浮点数的那个)

我遇到了orderedDictionary,但我不完全理解它们,也不知道它们对我的需求有多合适。我以为它们只是一个字典,允许您也索引到它们,但它们不是模板类吗?

按键自动排序对象的数据结构

你可能想要一个 SortedSet:http://msdn.microsoft.com/en-us/library/dd412070.aspx

如果您没有使用 .net 4.0,则在 PowerCollection 项目中可以使用它:http://powercollections.codeplex.com/

示例与 .Net4.0 排序集

SortedSet<float> set = new SortedSet<float>( );
set.Add(13.3f);
set.Add(0.5f);
set.Add(5.5f);
Console.WriteLine(string.Format("Minimum Value: {0}", set.Min)); // prints 0.5
Console.WriteLine(string.Format("Maximum Value: {0}", set.Max)); // prints 13.3
foreach (float f in set)
{
    Console.WriteLine(f);
}
// prints:
// 0.5
// 5.5
// 13.3
// using custom IComparer<float>, see implementation below
set = new SortedSet<float>(new FloatDescComparere());
set.Add(13.3f);
set.Add(0.5f);
set.Add(5.5f);
Console.WriteLine(string.Format("Minimum Value: {0}", set.Min)); // prints 13.3
Console.WriteLine(string.Format("Maximum Value: {0}", set.Max)); // prints 0.5
foreach (float f in set)
{
    Console.WriteLine(f);
}
// prints:
// 13.3
// 5.5
// 0.5

Desc IComparer:

private class FloatDescComparere : IComparer<float>
{
    public int Compare(float x, float y)
    {
        if (y > x)
            return 1;
        else if (x > y)
            return -1;
        else
            return 0;
    }
}
您可以使用

哈希表 http://en.wikipedia.org/wiki/Hash_table,将"key"放在哈希中并在哈希中搜索元素"key",如果哈希具有键,则您拥有该元素。每次添加新元素 O(1) 时都必须更新,但查找复杂度也为 O(1)。