2009-12-20 61 views
1

我需要一个有序的队列,其中的对象将按主值和辅助值进行排序。有两个索引的有序队列

class Object 
{ 
    int PrimaryValue; 
    int SecondaryValue; 
} 

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

回答

7
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()) ...

+0

马塞洛,我的意思是IEnumerator接口当然不是迭代器。 – 2009-12-20 13:58:40

+0

是的,我有点想,但谢谢你澄清它。你会发现'IEnumerator'在野外很少见到。它隐藏在普通代码的表面之下。 – 2009-12-20 23:53:06

2

听起来像你想要的是一个PriorityQueue,它的优先级是一个Pair或简单地说是一个带有自定义比较器的SortedList。这是一个PriorityQueue的实施,可以适应您的需求。由于GetEnumerator()返回IEnumerable,因此可以使用Reverse()扩展方法从后向前迭代它。

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

1

您可以只使用一个List<T>,并调用Sort(),但是,这样做,而不是在你的课堂上实施IComparable<T>。最后,如果您想反向枚举,请致电List<T>上的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); 
} 
}