开发者

Ordered queue with two indices

开发者 https://www.devze.com 2022-12-14 23:03 出处:网络
I need an ordered queue开发者_C百科 where objects would be ordered by primary and secondary value.

I need an ordered queue开发者_C百科 where objects would be ordered by primary and secondary value.

class Object
{
  int PrimaryValue;
  int SecondaryValue;
}

The position of an Object in the queue must be determined by PrimaryValue. Object with higher PrimaryValue must preceed object with lower PrimaryValue. However for two objects with the same PrimaryValue a SecondaryValue must be used to determine precedence. Also I need two functions to get forward iterator GetFirst() and backward iterator GetLast() that would return respective iterators.


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;
    }
}

I'm not sure quite what you mean by forward and reverse iterators, which is C++ jargon for concepts that don't really exist in C#. You can always iterate over a collection in the forward direction simply by using foreach (var e in coll) ..., and in reverse by using System.Linq: foreach (var e in coll.Reverse()) ....


Sounds like what you want is either a PriorityQueue with the priority being a Pair or simply a SortedList with a custom Comparer. Here's an implementation of a PriorityQueue that could be adapted to your needs. Since GetEnumerator() returns an IEnumerable you can use the Reverse() extension method to iterate over it from back to front.

Similarly with the SortedList -- you need only supply a suitable IComparer that performs the comparison you need and use Reverse() for back to front iteration.


You can just use a List<T>, and call Sort(), however, to do so, instead implement IComparable<T> on your class. Finally, if you want to enumerate in reverse, just call Reverse() on the List<T>.

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);
}
}


you just need a SortedList.... and to give it your own copareing thingy...

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号