wxArray, wxSortedArray combined

If you have a cool piece of software to share, but you are not hosting it officially yet, please dump it in here. If you have code snippets that are useful, please donate!
Post Reply
Peri
Experienced Solver
Experienced Solver
Posts: 91
Joined: Wed Nov 09, 2011 10:06 pm
Location: Seattle, USA

wxArray, wxSortedArray combined

Post by Peri » Sun Nov 20, 2011 7:31 pm

Ever want a base class with a wxArray where some of the derived classes need that array to be sorted and some not? The solution is simple, though it took quite a bit of time combing through the dynarray macros to get there.

The essence is to subclass wxSortedArray and provide overrides for functions which need to work either way - sorted or positional.

The following code has a sample MyType defined as int. At the bottom of the class are a bunch of base class functions which are being made hidden to clients - to prevent accidental usage in a wrong way. Of course, these could be made visible if needed.

Code: Select all

typedef int MyType;

WX_DEFINE_SORTED_ARRAY(MyType*, MyBaseArray);

//------------------------------------------------------------------------------
class MyArray : public MyBaseArray
{
protected:
  boolean isSorted;

public:
  
  //------------------------------------------------------------------------------
  MyArray (SCMPFUNCMyBaseArray comparer = NULL) : MyBaseArray (comparer)
  {
    isSorted = (comparer != NULL);
  }

  //------------------------------------------------------------------------------
  size_t Insert (MyType* item)
  {
    if (isSorted)
      return MyBaseArray::Add (item);
    else
    {
      size_t i = GetCount();
      MyArray::AddAt (item, i);
      return i;
    }
  }

  //------------------------------------------------------------------------------
  void InsertAt(MyType* item, size_t index)
  {
    wxASSERT (!isSorted);
    MyBaseArray::AddAt (item, index);
  }

  //------------------------------------------------------------------------------
  MyType* RemoveAt(size_t at)
  {
    MyType* item = MyBaseArray::Item (at);
    MyBaseArray::RemoveAt (at);
    return item;
  }

protected:
  void Add(MyType* item, size_t copies=1) {}
  void Add(MyType* &item, size_t copies=1) {}
  void AddAt(MyType* item, size_t index) {}
  MyType* Detach(size_t index) {}
  int Index(MyType* &item, bool searchFromEnd=false) {}
  int Index(MyType* &item) const {}
  int IndexForInsert(MyType* item) const {}
  void Insert(MyType* item, size_t n, size_t copies=1) {}
  void Insert(MyType* *item, size_t n) {}
  void Insert(MyType* &item, size_t n, size_t copies=1) {}
  void Remove(int item) {}
  void SetCount(size_t count, MyType* defval=NULL) {}
  void Sort(CMPFUNC compareFunction) {}
};

Post Reply