
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
610
|
Chapter 11: Data Structures and Algorithms
pqueue.DequeueSmallest( ): Message with odd characters
!@#$%^&*( )_+=-0987654321~|}{[]\\;:?/>.<,
pqueue.DequeueSmallest( ): <
>
A List<T> of string messages is created that will be used to fill the queue. A new
CompareLen IComparer<T> type object is created and passed in to the constructor of the
PriorityQueue<T>. If you did not pass in this IComparer<T> object, the output would
be much different: instead of items being retrieved from the queue based on length,
they would be retrieved based on their alphabetical order. (The
IComparer<T> inter-
face is covered in detail in the Discussion section.) Finally, a
foreach loop is used to
enqueue all messages into the
PriorityQueue<T> object.
At this point, the
PriorityQueue<T> object can be used in a manner similar to the
Queue<T> class contained in the FCL, except for the ability to remove items from both
the head and tail of the queue.
Discussion
You can instantiate the PriorityQueue<T> class with or without a special comparer
object. The special comparer object used in this recipe is defined in Example 11-3.
Example 11-3. Special CompareLen comparer class
public class CompareLen<T> : IComparer<T>
where T: IComparable<T>
{
public int Compare(T obj1, T obj2)
{
int result = 0;
if (typeof(T) == typeof(string)) ...