【问题标题】:Ordered queue with two indices具有两个索引的有序队列
【发布时间】:2009-12-20 13:29:54
【问题描述】:

我需要一个有序队列,其中对象将按主要值和次要值排序。

class Object
{
  int PrimaryValue;
  int SecondaryValue;
}

Object 在队列中的位置必须由 PrimaryValue 确定。具有较高 PrimaryValue 的对象必须在具有较低 PrimaryValue 的对象之前。但是,对于具有相同 PrimaryValue 的两个对象,必须使用 SecondaryValue 来确定优先级。我还需要两个函数来获取前向迭代器GetFirst() 和后向迭代器GetLast(),它们将返回各自的迭代器。

【问题讨论】:

    标签: c# data-structures queue


    【解决方案1】:
    class Obj : IComparable<Obj>
    {
        int PrimaryValue;
        int SecondaryValue;
    
        public int CompareTo(Obj other)
        {
            if (other == null) throw new ArgumentNullException("other");
            int diff = PrimaryValue - other.PrimaryValue;
            return diff != 0 ? diff : SecondaryValue - other.SecondaryValue;
        }
    }
    

    我不太清楚您所说的正向和反向迭代器是什么意思,这是 C++ 术语,表示 C# 中并不真正存在的概念。您始终可以通过使用 foreach (var e in coll) ... 向前迭代集合,并使用 System.Linq 反向迭代:foreach (var e in coll.Reverse()) ...

    【讨论】:

    • Marcelo,我指的是 IEnumerator 接口,当然不是迭代器。
    • 是的,我想通了,但还是感谢您的澄清。你会发现IEnumerator 在野外很少见。它隐藏在常规代码的表面之下。
    【解决方案2】:

    听起来您想要的是优先级为 Pair 的 PriorityQueue,或者只是带有自定义比较器的 SortedList。这是一个PriorityQueue 的实现,可以根据您的需要进行调整。由于 GetEnumerator() 返回一个 IEnumerable,您可以使用 Reverse() 扩展方法从后到前对其进行迭代。

    与 SortedList 类似——您只需要提供一个合适的 IComparer 来执行您需要的比较,并使用 Reverse() 进行从前到后的迭代。

    【讨论】:

      【解决方案3】:

      您可以只使用List&lt;T&gt;,然后调用Sort(),但要这样做,请在您的类上实现IComparable&lt;T&gt;。最后,如果您想反向枚举,只需在List&lt;T&gt; 上调用Reverse()

      public class MyObject : IComparable<MyObject>
      {
      public int First;
      public int Second;
      
      public int CompareTo(MyObject other)
      {
        if (Equals(this, other))
        {
          return 0;
        }
        if (ReferenceEquals(other, null))
        {
          return 1;
        }
        int first = this.First.CompareTo(other.First);
        if (first != 0)
        {
          return first;
        }
        return this.Second.CompareTo(other.Second);
      }
      }
      

      【讨论】:

        【解决方案4】:

        你只需要一个 SortedList.... 并给它你自己的东西......

        http://msdn.microsoft.com/en-us/library/ms132323.aspx

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-03
          • 1970-01-01
          相关资源
          最近更新 更多