Contents Up Previous Next

wxArray

This section describes the so called dynamic arrays. This is a C array-like data structure i.e. the member access time is constant (and not linear according to the number of container elements as for linked lists). However, these arrays are dynamic in the sense that they will automatically allocate more memory if there is not enough of it for adding a new element. They also perform range checking on the index values but in debug mode only, so please be sure to compile your application in debug mode to use it (see debugging overview for details). So, unlike the arrays in some other languages, attempt to access an element beyond the arrays bound doesn't automatically expand the array but provokes an assertion failure instead in debug build and does nothing (except possibly crashing your program) in the release build.

The array classes were designed to be reasonably efficient, both in terms of run-time speed and memory consumption and the executable size. The speed of array item access is, of course, constant (independent of the number of elements) making them much more efficient than linked lists (wxList). Adding items to the arrays is also implemented in more or less constant time - but the price is preallocating the memory in advance. In the memory management section you may find some useful hints about optimizing wxArray memory usage. As for executable size, all wxArray functions are inline, so they do not take any space at all.

wxWidgets has three different kinds of array. All of them derive from wxBaseArray class which works with untyped data and can not be used directly. The standard macros WX_DEFINE_ARRAY(), WX_DEFINE_SORTED_ARRAY() and WX_DEFINE_OBJARRAY() are used to define a new class deriving from it. The classes declared will be called in this documentation wxArray, wxSortedArray and wxObjArray but you should keep in mind that no classes with such names actually exist, each time you use one of WX_DEFINE_XXXARRAY macro you define a class with a new name. In fact, these names are "template" names and each usage of one of the macros mentioned above creates a template specialization for the given element type.

wxArray is suitable for storing integer types and pointers which it does not treat as objects in any way, i.e. the element pointed to by the pointer is not deleted when the element is removed from the array. It should be noted that all of wxArray's functions are inline, so it costs strictly nothing to define as many array types as you want (either in terms of the executable size or the speed) as long as at least one of them is defined and this is always the case because wxArrays are used by wxWidgets internally. This class has one serious limitation: it can only be used for storing integral types (bool, char, short, int, long and their unsigned variants) or pointers (of any kind). An attempt to use with objects of sizeof() greater than sizeof(long) will provoke a runtime assertion failure, however declaring a wxArray of floats will not (on the machines where sizeof(float) <= sizeof(long)), yet it will not work, please use wxObjArray for storing floats and doubles (NB: a more efficient wxArrayDouble class is scheduled for the next release of wxWidgets).

wxSortedArray is a wxArray variant which should be used when searching in the array is a frequently used operation. It requires you to define an additional function for comparing two elements of the array element type and always stores its items in the sorted order (according to this function). Thus, it is Index() function execution time is O(log(N)) instead of O(N) for the usual arrays but the Add() method is slower: it is O(log(N)) instead of constant time (neglecting time spent in memory allocation routine). However, in a usual situation elements are added to an array much less often than searched inside it, so wxSortedArray may lead to huge performance improvements compared to wxArray. Finally, it should be noticed that, as wxArray, wxSortedArray can be only used for storing integral types or pointers.

wxObjArray class treats its elements like "objects". It may delete them when they are removed from the array (invoking the correct destructor) and copies them using the objects copy constructor. In order to implement this behaviour the definition of the wxObjArray arrays is split in two parts: first, you should declare the new wxObjArray class using WX_DECLARE_OBJARRAY() macro and then you must include the file defining the implementation of template type: <wx/arrimpl.cpp> and define the array class with WX_DEFINE_OBJARRAY() macro from a point where the full (as opposed to 'forward') declaration of the array elements class is in scope. As it probably sounds very complicated here is an example:

#include <wx/dynarray.h>

// we must forward declare the array because it is used inside the class
// declaration
class MyDirectory;
class MyFile;

// this defines two new types: ArrayOfDirectories and ArrayOfFiles which can be
// now used as shown below
WX_DECLARE_OBJARRAY(MyDirectory, ArrayOfDirectories);
WX_DECLARE_OBJARRAY(MyFile,      ArrayOfFiles);

class MyDirectory
{
...
    ArrayOfDirectories m_subdirectories; // all subdirectories
    ArrayOfFiles       m_files;          // all files in this directory
};

...

// now that we have MyDirectory declaration in scope we may finish the
// definition of ArrayOfDirectories -- note that this expands into some C++
// code and so should only be compiled once (i.e., don't put this in the
// header, but into a source file or you will get linking errors)
#include <wx/arrimpl.cpp> // this is a magic incantation which must be done!
WX_DEFINE_OBJARRAY(ArrayOfDirectories);

// that's all!
It is not as elegant as writing

typedef std::vector<MyDirectory> ArrayOfDirectories;
but is not that complicated and allows the code to be compiled with any, however dumb, C++ compiler in the world.

Things are much simpler for wxArray and wxSortedArray however: it is enough just to write

WX_DEFINE_ARRAY(int, ArrayOfDirectories);
WX_DEFINE_SORTED_ARRAY(int, ArrayOfFiles);
i.e. there is only one DEFINE macro and no need for separate DECLARE one.

See also:

Container classes overview, wxList

Include files

<wx/dynarray.h> for wxArray and wxSortedArray and additionally <wx/arrimpl.cpp> for wxObjArray.

Function groups

Macros for template array definition
Constructors and destructors
Memory management
Number of elements and simple item access
Adding items
Removing items
Searching and sorting
WX_DEFINE_ARRAY
WX_DEFINE_SORTED_ARRAY
WX_DECLARE_OBJARRAY
WX_DEFINE_OBJARRAY
WX_APPEND_ARRAY
WX_CLEAR_ARRAY
Default constructors
wxArray copy constructor and assignment operator
wxArray::~wxArray
wxArray::Add
wxArray::Alloc
wxArray::Clear
wxArray::Count
wxObjArray::Detach
wxArray::Empty
wxArray::GetCount
wxArray::Index
wxArray::Insert
wxArray::IsEmpty
wxArray::Item
wxArray::Last
wxArray::Remove
wxArray::RemoveAt
wxArray::SetCount
wxArray::Shrink
wxArray::Sort


Macros for template array definition

To use an array you must first define the array class. This is done with the help of the macros in this section. The class of array elements must be (at least) forward declared for WX_DEFINE_ARRAY, WX_DEFINE_SORTED_ARRAY and WX_DECLARE_OBJARRAY macros and must be fully declared before you use WX_DEFINE_OBJARRAY macro.

WX_DEFINE_ARRAY
WX_DEFINE_EXPORTED_ARRAY
WX_DEFINE_USER_EXPORTED_ARRAY
WX_DEFINE_SORTED_ARRAY
WX_DEFINE_SORTED_EXPORTED_ARRAY
WX_DEFINE_SORTED_USER_EXPORTED_ARRAY
WX_DECLARE_EXPORTED_OBJARRAY
WX_DECLARE_USER_EXPORTED_OBJARRAY
WX_DEFINE_OBJARRAY
WX_DEFINE_EXPORTED_OBJARRAY
WX_DEFINE_USER_EXPORTED_OBJARRAY

To slightly complicate the matters even further, the operator -> defined by default for the array iterators by these macros only makes sense if the array element type is not a pointer itself and, although it still works, this provokes warnings from some compilers and to avoid them you should use the _PTR versions of the macros above. For example, to define an array of pointers to double you should use.

If that isn't complicated enough, the above macros are generally only useful for wxObject types. There are seperate macros for declaring an array of a simple type, such as an int.

The following simple types are supported: int
long
size_t
double

To create an array of a simple type, simply append the type you want in CAPS to the array definition.

For example, for an integer array, you'd use one of the following variants:

WX_DEFINE_ARRAY_INT
WX_DEFINE_EXPORTED_ARRAY_INT
WX_DEFINE_USER_EXPORTED_ARRAY_INT
WX_DEFINE_SORTED_ARRAY_INT
WX_DEFINE_SORTED_EXPORTED_ARRAY_INT
WX_DEFINE_SORTED_USER_EXPORTED_ARRAY_INT

WX_DEFINE_ARRAY_PTR(double *, MyArrayOfDoublePointers);

Constructors and destructors

Array classes are 100% C++ objects and as such they have the appropriate copy constructors and assignment operators. Copying wxArray just copies the elements but copying wxObjArray copies the arrays items. However, for memory-efficiency sake, neither of these classes has virtual destructor. It is not very important for wxArray which has trivial destructor anyhow, but it does mean that you should avoid deleting wxObjArray through a wxBaseArray pointer (as you would never use wxBaseArray anyhow it shouldn't be a problem) and that you should not derive your own classes from the array classes.

wxArray default constructor
wxArray copy constructors and assignment operators
~wxArray


Memory management

Automatic array memory management is quite trivial: the array starts by preallocating some minimal amount of memory (defined by WX_ARRAY_DEFAULT_INITIAL_SIZE) and when further new items exhaust already allocated memory it reallocates it adding 50% of the currently allocated amount, but no more than some maximal number which is defined by ARRAY_MAXSIZE_INCREMENT constant. Of course, this may lead to some memory being wasted (ARRAY_MAXSIZE_INCREMENT in the worst case, i.e. 4Kb in the current implementation), so the Shrink() function is provided to deallocate the extra memory. The Alloc() function can also be quite useful if you know in advance how many items you are going to put in the array and will prevent the array code from reallocating the memory more times than needed.

Alloc
Shrink


Number of elements and simple item access

Functions in this section return the total number of array elements and allow to retrieve them - possibly using just the C array indexing [] operator which does exactly the same as Item() method.

Count
GetCount
IsEmpty
Item
Last


Adding items

Add
Insert
SetCount
WX_APPEND_ARRAY


Removing items

WX_CLEAR_ARRAY
Empty
Clear
RemoveAt
Remove


Searching and sorting

Index
Sort


WX_DEFINE_ARRAY

WX_DEFINE_ARRAY(T, name)

WX_DEFINE_EXPORTED_ARRAY(T, name)

WX_DEFINE_USER_EXPORTED_ARRAY(T, name, exportspec)

This macro defines a new array class named name and containing the elements of type T. The second form is used when compiling wxWidgets as a DLL under Windows and array needs to be visible outside the DLL. The third is needed for exporting an array from a user DLL.

Example:

WX_DEFINE_ARRAY_INT(wxArrayInt);

class MyClass;
WX_DEFINE_ARRAY(MyClass *, wxArrayOfMyClass);
Note that wxWidgets predefines the following standard array classes: wxArrayInt, wxArrayLong and wxArrayPtrVoid.


WX_DEFINE_SORTED_ARRAY

WX_DEFINE_SORTED_ARRAY(T, name)

WX_DEFINE_SORTED_EXPORTED_ARRAY(T, name)

WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(T, name)

This macro defines a new sorted array class named name and containing the elements of type T. The second form is used when compiling wxWidgets as a DLL under Windows and array needs to be visible outside the DLL. The third is needed for exporting an array from a user DLL.

Example:

WX_DEFINE_SORTED_ARRAY_INT(wxSortedArrayInt);

class MyClass;
WX_DEFINE_SORTED_ARRAY(MyClass *, wxArrayOfMyClass);
You will have to initialize the objects of this class by passing a comparison function to the array object constructor like this:

int CompareInts(int n1, int n2)
{
    return n1 - n2;
}

wxSortedArrayInt sorted(CompareInts);

int CompareMyClassObjects(MyClass *item1, MyClass *item2)
{
    // sort the items by their address...
    return Stricmp(item1->GetAddress(), item2->GetAddress());
}

wxArrayOfMyClass another(CompareMyClassObjects);

WX_DECLARE_OBJARRAY

WX_DECLARE_OBJARRAY(T, name)

WX_DECLARE_EXPORTED_OBJARRAY(T, name)

WX_DECLARE_USER_EXPORTED_OBJARRAY(T, name)

This macro declares a new object array class named name and containing the elements of type T. The second form is used when compiling wxWidgets as a DLL under Windows and array needs to be visible outside the DLL. The third is needed for exporting an array from a user DLL.

Example:

class MyClass;
WX_DECLARE_OBJARRAY(MyClass, wxArrayOfMyClass); // note: not "MyClass *"!
You must use WX_DEFINE_OBJARRAY() macro to define the array class - otherwise you would get link errors.


WX_DEFINE_OBJARRAY

WX_DEFINE_OBJARRAY(name)

WX_DEFINE_EXPORTED_OBJARRAY(name)

WX_DEFINE_USER_EXPORTED_OBJARRAY(name)

This macro defines the methods of the array class name not defined by the WX_DECLARE_OBJARRAY() macro. You must include the file <wx/arrimpl.cpp> before using this macro and you must have the full declaration of the class of array elements in scope! If you forget to do the first, the error will be caught by the compiler, but, unfortunately, many compilers will not give any warnings if you forget to do the second - but the objects of the class will not be copied correctly and their real destructor will not be called. The latter two forms are merely aliases of the first to satisfy some people's sense of symmetry when using the exported declarations.

Example of usage:

// first declare the class!
class MyClass
{
public:
   MyClass(const MyClass&);

   ...

   virtual ~MyClass();
};

#include <wx/arrimpl.cpp>
WX_DEFINE_OBJARRAY(wxArrayOfMyClass);

WX_APPEND_ARRAY

void WX_APPEND_ARRAY(wxArray& array, wxArray& other)

This macro may be used to append all elements of the other array to the array. The two arrays must be of the same type.


WX_CLEAR_ARRAY

void WX_CLEAR_ARRAY(wxArray& array)

This macro may be used to delete all elements of the array before emptying it. It can not be used with wxObjArrays - but they will delete their elements anyhow when you call Empty().


Default constructors

wxArray()

wxObjArray()

Default constructor initializes an empty array object.

wxSortedArray(int (*)(T first, T second)compareFunction)

There is no default constructor for wxSortedArray classes - you must initialize it with a function to use for item comparison. It is a function which is passed two arguments of type T where T is the array element type and which should return a negative, zero or positive value according to whether the first element passed to it is less than, equal to or greater than the second one.


wxArray copy constructor and assignment operator

wxArray(const wxArray& array)

wxSortedArray(const wxSortedArray& array)

wxObjArray(const wxObjArray& array)

wxArray& operator=(const wxArray& array)

wxSortedArray& operator=(const wxSortedArray& array)

wxObjArray& operator=(const wxObjArray& array)

The copy constructors and assignment operators perform a shallow array copy (i.e. they don't copy the objects pointed to even if the source array contains the items of pointer type) for wxArray and wxSortedArray and a deep copy (i.e. the array element are copied too) for wxObjArray.


wxArray::~wxArray

~wxArray()

~wxSortedArray()

~wxObjArray()

The wxObjArray destructor deletes all the items owned by the array. This is not done by wxArray and wxSortedArray versions - you may use WX_CLEAR_ARRAY macro for this.


wxArray::Add

void Add(T item, size_t copies = 1)

void Add(T *item)

void Add(T &item, size_t copies = 1)

Appends the given number of copies of the item to the array consisting of the elements of type T.

The first version is used with wxArray and wxSortedArray. The second and the third are used with wxObjArray. There is an important difference between them: if you give a pointer to the array, it will take ownership of it, i.e. will delete it when the item is deleted from the array. If you give a reference to the array, however, the array will make a copy of the item and will not take ownership of the original item. Once again, it only makes sense for wxObjArrays because the other array types never take ownership of their elements. Also note that you cannot append more than one pointer as reusing it would lead to deleting it twice (or more) and hence to a crash.

You may also use WX_APPEND_ARRAY macro to append all elements of one array to another one but it is more efficient to use copies parameter and modify the elements in place later if you plan to append a lot of items.


wxArray::Alloc

void Alloc(size_t count)

Preallocates memory for a given number of array elements. It is worth calling when the number of items which are going to be added to the array is known in advance because it will save unneeded memory reallocation. If the array already has enough memory for the given number of items, nothing happens.


wxArray::Clear

void Clear()

This function does the same as Empty() and additionally frees the memory allocated to the array.


wxArray::Count

size_t Count() const

Same as GetCount(). This function is deprecated - it exists only for compatibility.


wxObjArray::Detach

T * Detach(size_t index)

Removes the element from the array, but, unlike, Remove() doesn't delete it. The function returns the pointer to the removed element.


wxArray::Empty

void Empty()

Empties the array. For wxObjArray classes, this destroys all of the array elements. For wxArray and wxSortedArray this does nothing except marking the array of being empty - this function does not free the allocated memory, use Clear() for this.


wxArray::GetCount

size_t GetCount() const

Return the number of items in the array.


wxArray::Index

int Index(T& item, bool searchFromEnd = false)

int Index(T& item)

The first version of the function is for wxArray and wxObjArray, the second is for wxSortedArray only.

Searches the element in the array, starting from either beginning or the end depending on the value of searchFromEnd parameter. wxNOT_FOUND is returned if the element is not found, otherwise the index of the element is returned.

Linear search is used for the wxArray and wxObjArray classes but binary search in the sorted array is used for wxSortedArray (this is why searchFromEnd parameter doesn't make sense for it).

NB: even for wxObjArray classes, the operator==() of the elements in the array is not used by this function. It searches exactly the given element in the array and so will only succeed if this element had been previously added to the array, but fail even if another, identical, element is in the array.


wxArray::Insert

void Insert(T item, size_t n, size_t copies = 1)

void Insert(T *item, size_t n)

void Insert(T &item, size_t n, size_t copies = 1)

Insert the given number of copies of the item into the array before the existing item n - thus, Insert(something, 0u) will insert an item in such way that it will become the first array element.

Please see Add() for explanation of the differences between the overloaded versions of this function.


wxArray::IsEmpty

bool IsEmpty() const

Returns true if the array is empty, false otherwise.


wxArray::Item

T& Item(size_t index) const

Returns the item at the given position in the array. If index is out of bounds, an assert failure is raised in the debug builds but nothing special is done in the release build.

The returned value is of type "reference to the array element type" for all of the array classes.


wxArray::Last

T& Last() const

Returns the last element in the array, i.e. is the same as Item(GetCount() - 1). An assert failure is raised in the debug mode if the array is empty.

The returned value is of type "reference to the array element type" for all of the array classes.


wxArray::Remove

Remove(T item)

Removes an element from the array by value: the first item of the array equal to item is removed, an assert failure will result from an attempt to remove an item which doesn't exist in the array.

When an element is removed from wxObjArray it is deleted by the array - use Detach() if you don't want this to happen. On the other hand, when an object is removed from a wxArray nothing happens - you should delete it manually if required:

T *item = array[n];
delete item;
array.Remove(n)
See also WX_CLEAR_ARRAY macro which deletes all elements of a wxArray (supposed to contain pointers).


wxArray::RemoveAt

RemoveAt(size_t index, size_t count = 1)

Removes count elements starting at index from the array. When an element is removed from wxObjArray it is deleted by the array - use Detach() if you don't want this to happen. On the other hand, when an object is removed from a wxArray nothing happens - you should delete it manually if required:

T *item = array[n];
delete item;
array.RemoveAt(n)
See also WX_CLEAR_ARRAY macro which deletes all elements of a wxArray (supposed to contain pointers).


wxArray::SetCount

void SetCount(size_t count, T defval = T(0))

This function ensures that the number of array elements is at least count. If the array has already count or mroe items, nothing is done. Otherwise, count - GetCount() elements are added and initialized to the value defval.

See also

GetCount


wxArray::Shrink

void Shrink()

Frees all memory unused by the array. If the program knows that no new items will be added to the array it may call Shrink() to reduce its memory usage. However, if a new item is added to the array, some extra memory will be allocated again.


wxArray::Sort

void Sort(CMPFUNC<T> compareFunction)

The notation CMPFUNC<T> should be read as if we had the following declaration:

template int CMPFUNC(T *first, T *second);
where T is the type of the array elements. I.e. it is a function returning int which is passed two arguments of type T *.

Sorts the array using the specified compare function: this function should return a negative, zero or positive value according to whether the first element passed to it is less than, equal to or greater than the second one.

wxSortedArray doesn't have this function because it is always sorted.