Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleMake a sorted collection class
Keywordssorting, algorithms, sorted collection class, SortedCollection class
CategoriesAlgorithms
 
See the book Ready-to-Run Visual Basic Algorithms for more information on this and other sorting algorithms.

This class stores items in a normal collection. It inserts items in their proper places in the collection.

 
' Add an item at its correct position.
Public Sub AddItem(ByVal new_item As String)
Dim i As Integer

    ' See where the item belongs.
    For i = 1 To m_Items.Count
        If m_Items(i) >= new_item Then Exit For
    Next i

    ' Insert the item.
    If i > m_Items.Count Then
        ' Add at the end.
        m_Items.Add new_item
    Else
        ' Add at the right position.
        m_Items.Add new_item, , i
    End If
End Sub
 
The main reason the class stores items in a collection rather than an array, linked list, or some other data structures is to provide the For Each operator. To do that, the class must provide a NewEnum function that returns an IUnknown interface object. The class can get such an object from a normal collection like this:
 
Public Function NewEnum() As IUnknown
    Set NewEnum = m_Items.[_NewEnum]
End Function
 
To register this function as the class enumerator, you must:

  1. Open the SortedCollection's class editor window.
  2. Select the Tools menu's Procedure Attributes command.
    1. Select NewEnum in the Name box.
    2. Click Advanced >>
    3. Click on the Procedure ID box and type -4.
    4. Check the "Hide this member" box so the user cannot see this method (it's really only useful indirectly via For each).
    5. Click Ok.

The Count, Remove, and Item methods are simply delegated to the m_Items collection.

 
    ' Return the number of items.
    Public Function Count() As Integer
        Count = m_Items.Count
    End Function

    ' Remove an item.
    Public Sub Remove(ByVal Index As Integer)
        m_Items.Remove Index
    End Sub

    ' Return an item.
    Public Function Item(ByVal Index As Integer) As String
        Item = m_Items(Index)
    End Function
 
The class makes its Item method its default method. That allows a program using it to refer to items as in:

    sorted_collection(K)

in addition to:

    sorted_collection.Item(K)

To make Item be the default method, you must:

  1. Open the SortedCollection's class editor window.
  2. Select the Tools menu's Procedure Attributes command.
    1. Select Item in the Name box.
    2. Click Advanced >>
    3. Select (Default) in the Procedure ID box.
    4. Click Ok.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated