]>
git.saurik.com Git - wxWidgets.git/blob - interface/wx/dynarray.h
1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: interface of wxArray<T>
4 // Author: wxWidgets team
6 // Licence: wxWindows license
7 /////////////////////////////////////////////////////////////////////////////
11 This section describes the so called @e "dynamic arrays". This is a C
12 array-like type safe data structure i.e. the member access time is constant
13 (and not linear according to the number of container elements as for linked
14 lists). However, these arrays are dynamic in the sense that they will
15 automatically allocate more memory if there is not enough of it for adding
16 a new element. They also perform range checking on the index values but in
17 debug mode only, so please be sure to compile your application in debug
18 mode to use it (see @ref overview_debugging for details). So, unlike the
19 arrays in some other languages, attempt to access an element beyond the
20 arrays bound doesn't automatically expand the array but provokes an
21 assertion failure instead in debug build and does nothing (except possibly
22 crashing your program) in the release build.
24 The array classes were designed to be reasonably efficient, both in terms
25 of run-time speed and memory consumption and the executable size. The speed
26 of array item access is, of course, constant (independent of the number of
27 elements) making them much more efficient than linked lists (wxList).
28 Adding items to the arrays is also implemented in more or less constant
29 time, but the price is preallocating the memory in advance. In the
30 "memory management" function section, you may find some useful hints about
31 optimizing wxArray memory usage. As for executable size, all wxArray
32 functions are inline, so they do not take @e any space at all.
34 wxWidgets has three different kinds of array. All of them derive from
35 wxBaseArray class which works with untyped data and can not be used
36 directly. The standard macros WX_DEFINE_ARRAY(), WX_DEFINE_SORTED_ARRAY()
37 and WX_DEFINE_OBJARRAY() are used to define a new class deriving from it.
38 The classes declared will be called in this documentation wxArray,
39 wxSortedArray and wxObjArray but you should keep in mind that no classes
40 with such names actually exist, each time you use one of the
41 WX_DEFINE_XXXARRAY() macros, you define a class with a new name. In fact,
42 these names are "template" names and each usage of one of the macros
43 mentioned above creates a template specialization for the given element
46 wxArray is suitable for storing integer types and pointers which it does
47 not treat as objects in any way, i.e. the element pointed to by the pointer
48 is not deleted when the element is removed from the array. It should be
49 noted that all of wxArray's functions are inline, so it costs strictly
50 nothing to define as many array types as you want (either in terms of the
51 executable size or the speed) as long as at least one of them is defined
52 and this is always the case because wxArrays are used by wxWidgets
53 internally. This class has one serious limitation: it can only be used for
54 storing integral types (bool, char, short, int, long and their unsigned
55 variants) or pointers (of any kind). An attempt to use with objects of
56 @c sizeof() greater than @c sizeof(long) will provoke a runtime assertion
57 failure, however declaring a wxArray of floats will not (on the machines
58 where @c "sizeof(float) <= sizeof(long)"), yet it will @b not work, please
59 use wxObjArray for storing floats and doubles.
61 wxSortedArray is a wxArray variant which should be used when searching in
62 the array is a frequently used operation. It requires you to define an
63 additional function for comparing two elements of the array element type
64 and always stores its items in the sorted order (according to this
65 function). Thus, its Index() function execution time is @c "O(log(N))"
66 instead of @c "O(N)" for the usual arrays but the Add() method is slower:
67 it is @c "O(log(N))" instead of constant time (neglecting time spent in
68 memory allocation routine). However, in a usual situation elements are
69 added to an array much less often than searched inside it, so wxSortedArray
70 may lead to huge performance improvements compared to wxArray. Finally, it
71 should be noticed that, as wxArray, wxSortedArray can be only used for
72 storing integral types or pointers.
74 wxObjArray class treats its elements like "objects". It may delete them
75 when they are removed from the array (invoking the correct destructor) and
76 copies them using the objects copy constructor. In order to implement this
77 behaviour the definition of the wxObjArray arrays is split in two parts:
78 first, you should declare the new wxObjArray class using the
79 WX_DECLARE_OBJARRAY() macro and then you must include the file defining the
80 implementation of template type: @<wx/arrimpl.cpp@> and define the array
81 class with the WX_DEFINE_OBJARRAY() macro from a point where the full (as
82 opposed to 'forward') declaration of the array elements class is in scope.
83 As it probably sounds very complicated here is an example:
86 #include <wx/dynarray.h>
88 // We must forward declare the array because it is used
89 // inside the class declaration.
93 // This defines two new types: ArrayOfDirectories and ArrayOfFiles which
94 // can be now used as shown below.
95 WX_DECLARE_OBJARRAY(MyDirectory, ArrayOfDirectories);
96 WX_DECLARE_OBJARRAY(MyFile, ArrayOfFiles);
101 ArrayOfDirectories m_subdirectories; // All subdirectories
102 ArrayOfFiles m_files; // All files in this directory
107 // Now that we have MyDirectory declaration in scope we may finish the
108 // definition of ArrayOfDirectories -- note that this expands into some C++
109 // code and so should only be compiled once (i.e., don't put this in the
110 // header, but into a source file or you will get linking errors)
111 #include <wx/arrimpl.cpp> // This is a magic incantation which must be done!
112 WX_DEFINE_OBJARRAY(ArrayOfDirectories);
117 It is not as elegant as writing this:
120 typedef std::vector<MyDirectory> ArrayOfDirectories;
123 But is not that complicated and allows the code to be compiled with any,
124 however dumb, C++ compiler in the world.
126 Remember to include @<wx/arrimpl.cpp@> just before each
127 WX_DEFINE_OBJARRAY() ocurrence in your code, even if you have several in
130 Things are much simpler for wxArray and wxSortedArray however: it is enough
134 WX_DEFINE_ARRAY_INT(int, ArrayOfInts);
135 WX_DEFINE_SORTED_ARRAY_INT(int, ArrayOfSortedInts);
138 There is only one @c DEFINE macro and no need for separate @c DECLARE one.
139 For the arrays of the primitive types, the macros
140 @c WX_DEFINE_ARRAY_CHAR/SHORT/INT/SIZE_T/LONG/DOUBLE should be used
141 depending on the sizeof of the values (notice that storing values of
142 smaller type, e.g. shorts, in an array of larger one, e.g. @c ARRAY_INT,
143 does not work on all architectures!).
146 @section array_macros Macros for Template Array Definition
148 To use an array you must first define the array class. This is done with
149 the help of the macros in this section. The class of array elements must be
150 (at least) forward declared for WX_DEFINE_ARRAY(), WX_DEFINE_SORTED_ARRAY()
151 and WX_DECLARE_OBJARRAY() macros and must be fully declared before you use
152 WX_DEFINE_OBJARRAY() macro.
155 - WX_DEFINE_EXPORTED_ARRAY()
156 - WX_DEFINE_USER_EXPORTED_ARRAY()
157 - WX_DEFINE_SORTED_ARRAY()
158 - WX_DEFINE_SORTED_EXPORTED_ARRAY()
159 - WX_DEFINE_SORTED_USER_EXPORTED_ARRAY()
160 - WX_DECLARE_EXPORTED_OBJARRAY()
161 - WX_DECLARE_USER_EXPORTED_OBJARRAY()
162 - WX_DEFINE_OBJARRAY()
163 - WX_DEFINE_EXPORTED_OBJARRAY()
164 - WX_DEFINE_USER_EXPORTED_OBJARRAY()
166 To slightly complicate the matters even further, the operator "->" defined
167 by default for the array iterators by these macros only makes sense if the
168 array element type is not a pointer itself and, although it still works,
169 this provokes warnings from some compilers and to avoid them you should use
170 the @c _PTR versions of the macros above. For example, to define an array
171 of pointers to @c double you should use:
174 WX_DEFINE_ARRAY_PTR(double *, MyArrayOfDoublePointers);
177 Note that the above macros are generally only useful for wxObject types.
178 There are separate macros for declaring an array of a simple type, such as
181 The following simple types are supported:
187 To create an array of a simple type, simply append the type you want in
188 CAPS to the array definition.
190 For example, you'd use one of the following variants for an integer array:
192 - WX_DEFINE_ARRAY_INT()
193 - WX_DEFINE_EXPORTED_ARRAY_INT()
194 - WX_DEFINE_USER_EXPORTED_ARRAY_INT()
195 - WX_DEFINE_SORTED_ARRAY_INT()
196 - WX_DEFINE_SORTED_EXPORTED_ARRAY_INT()
197 - WX_DEFINE_SORTED_USER_EXPORTED_ARRAY_INT()
201 @category{containers}
203 @see @ref overview_container, wxList<T>, wxVector<T>
209 @name Constructors and Destructors
211 Array classes are 100% C++ objects and as such they have the
212 appropriate copy constructors and assignment operators. Copying wxArray
213 just copies the elements but copying wxObjArray copies the arrays
214 items. However, for memory-efficiency sake, neither of these classes
215 has virtual destructor. It is not very important for wxArray which has
216 trivial destructor anyhow, but it does mean that you should avoid
217 deleting wxObjArray through a wxBaseArray pointer (as you would never
218 use wxBaseArray anyhow it shouldn't be a problem) and that you should
219 not derive your own classes from the array classes.
229 Default constructor initializes an empty array object.
234 There is no default constructor for wxSortedArray classes - you must
235 initialize it with a function to use for item comparison. It is a
236 function which is passed two arguments of type @c T where @c T is the
237 array element type and which should return a negative, zero or positive
238 value according to whether the first element passed to it is less than,
239 equal to or greater than the second one.
241 wxSortedArray(int (*)(T first
, T second
)compareFunction
);
244 Performs a shallow array copy (i.e. doesn't copy the objects pointed to
245 even if the source array contains the items of pointer type).
247 wxArray(const wxArray
& array
);
250 Performs a shallow array copy (i.e. doesn't copy the objects pointed to
251 even if the source array contains the items of pointer type).
253 wxSortedArray(const wxSortedArray
& array
);
256 Performs a deep copy (i.e. the array element are copied too).
258 wxObjArray(const wxObjArray
& array
);
261 Performs a shallow array copy (i.e. doesn't copy the objects pointed to
262 even if the source array contains the items of pointer type).
264 wxArray
& operator=(const wxArray
& array
);
267 Performs a shallow array copy (i.e. doesn't copy the objects pointed to
268 even if the source array contains the items of pointer type).
270 wxSortedArray
& operator=(const wxSortedArray
& array
);
273 Performs a deep copy (i.e. the array element are copied too).
275 wxObjArray
& operator=(const wxObjArray
& array
);
278 This destructor does not delete all the items owned by the array, you
279 may use the WX_CLEAR_ARRAY() macro for this.
284 This destructor does not delete all the items owned by the array, you
285 may use the WX_CLEAR_ARRAY() macro for this.
290 This destructor deletes all the items owned by the array.
298 @name Memory Management
300 Automatic array memory management is quite trivial: the array starts by
301 preallocating some minimal amount of memory (defined by
302 @c WX_ARRAY_DEFAULT_INITIAL_SIZE) and when further new items exhaust
303 already allocated memory it reallocates it adding 50% of the currently
304 allocated amount, but no more than some maximal number which is defined
305 by the @c ARRAY_MAXSIZE_INCREMENT constant. Of course, this may lead to
306 some memory being wasted (@c ARRAY_MAXSIZE_INCREMENT in the worst case,
307 i.e. 4Kb in the current implementation), so the Shrink() function is
308 provided to deallocate the extra memory. The Alloc() function can also
309 be quite useful if you know in advance how many items you are going to
310 put in the array and will prevent the array code from reallocating the
311 memory more times than needed.
316 Preallocates memory for a given number of array elements. It is worth
317 calling when the number of items which are going to be added to the
318 array is known in advance because it will save unneeded memory
319 reallocation. If the array already has enough memory for the given
320 number of items, nothing happens. In any case, the existing contents of
321 the array is not modified.
323 void Alloc(size_t count
);
326 Frees all memory unused by the array. If the program knows that no new
327 items will be added to the array it may call Shrink() to reduce its
328 memory usage. However, if a new item is added to the array, some extra
329 memory will be allocated again.
337 @name Number of Elements and Simple Item Access
339 Functions in this section return the total number of array elements and
340 allow to retrieve them - possibly using just the C array indexing []
341 operator which does exactly the same as the Item() method.
346 Return the number of items in the array.
348 size_t GetCount() const;
351 Returns @true if the array is empty, @false otherwise.
353 bool IsEmpty() const;
356 Returns the item at the given position in the array. If @a index is out
357 of bounds, an assert failure is raised in the debug builds but nothing
358 special is done in the release build.
360 The returned value is of type "reference to the array element type" for
361 all of the array classes.
363 T
& Item(size_t index
) const;
366 Returns the last element in the array, i.e. is the same as calling
367 "Item(GetCount() - 1)". An assert failure is raised in the debug mode
368 if the array is empty.
370 The returned value is of type "reference to the array element type" for
371 all of the array classes.
384 Appends the given number of @a copies of the @a item to the array
385 consisting of the elements of type @c T.
387 This version is used with wxArray.
389 You may also use WX_APPEND_ARRAY() macro to append all elements of one
390 array to another one but it is more efficient to use the @a copies
391 parameter and modify the elements in place later if you plan to append
394 void Add(T item
, size_t copies
= 1);
397 Appends the @a item to the array consisting of the elements of type
400 This version is used with wxSortedArray, returning the index where
406 Appends the @a item to the array consisting of the elements of type
409 This version is used with wxObjArray. The array will take ownership of
410 the @a item, deleting it when the item is deleted from the array. Note
411 that you cannot append more than one pointer as reusing it would lead
412 to deleting it twice (or more) resulting in a crash.
414 You may also use WX_APPEND_ARRAY() macro to append all elements of one
415 array to another one but it is more efficient to use the @a copies
416 parameter and modify the elements in place later if you plan to append
422 Appends the given number of @a copies of the @a item to the array
423 consisting of the elements of type @c T.
425 This version is used with wxObjArray. The array will make a copy of the
426 item and will not take ownership of the original item.
428 You may also use WX_APPEND_ARRAY() macro to append all elements of one
429 array to another one but it is more efficient to use the @a copies
430 parameter and modify the elements in place later if you plan to append
433 void Add(T
& item
, size_t copies
= 1);
436 Inserts the given @a item into the array in the specified @e index
439 Be aware that you will set out the order of the array if you give a
442 This function is useful in conjunction with IndexForInsert() for a
443 common operation of "insert only if not found".
445 void AddAt(T item
, size_t index
);
448 Insert the given number of @a copies of the @a item into the array
449 before the existing item @a n - thus, @e Insert(something, 0u) will
450 insert an item in such way that it will become the first array element.
452 wxSortedArray doesn't have this function because inserting in wrong
453 place would break its sorted condition.
455 Please see Add() for an explanation of the differences between the
456 overloaded versions of this function.
458 void Insert(T item
, size_t n
, size_t copies
= 1);
461 Insert the @a item into the array before the existing item @a n - thus,
462 @e Insert(something, 0u) will insert an item in such way that it will
463 become the first array element.
465 wxSortedArray doesn't have this function because inserting in wrong
466 place would break its sorted condition.
468 Please see Add() for an explanation of the differences between the
469 overloaded versions of this function.
471 void Insert(T
* item
, size_t n
);
474 Insert the given number of @a copies of the @a item into the array
475 before the existing item @a n - thus, @e Insert(something, 0u) will
476 insert an item in such way that it will become the first array element.
478 wxSortedArray doesn't have this function because inserting in wrong
479 place would break its sorted condition.
481 Please see Add() for an explanation of the differences between the
482 overloaded versions of this function.
484 void Insert(T
& item
, size_t n
, size_t copies
= 1);
487 This function ensures that the number of array elements is at least
488 @a count. If the array has already @a count or more items, nothing is
489 done. Otherwise, @a count - GetCount() elements are added and
490 initialized to the value @a defval.
494 void SetCount(size_t count
, T defval
= T(0));
505 This function does the same as Empty() and additionally frees the
506 memory allocated to the array.
511 Removes the element from the array, but unlike Remove(), it doesn't
512 delete it. The function returns the pointer to the removed element.
514 T
* Detach(size_t index
);
517 Empties the array. For wxObjArray classes, this destroys all of the
518 array elements. For wxArray and wxSortedArray this does nothing except
519 marking the array of being empty - this function does not free the
520 allocated memory, use Clear() for this.
525 Removes an element from the array by value: the first item of the array
526 equal to @a item is removed, an assert failure will result from an
527 attempt to remove an item which doesn't exist in the array.
529 When an element is removed from wxObjArray it is deleted by the array -
530 use Detach() if you don't want this to happen. On the other hand, when
531 an object is removed from a wxArray nothing happens - you should delete
532 it manually if required:
540 See also WX_CLEAR_ARRAY() macro which deletes all elements of a wxArray
541 (supposed to contain pointers).
546 Removes @a count elements starting at @a index from the array. When an
547 element is removed from wxObjArray it is deleted by the array - use
548 Detach() if you don't want this to happen. On the other hand, when an
549 object is removed from a wxArray nothing happens - you should delete it
550 manually if required:
558 See also WX_CLEAR_ARRAY() macro which deletes all elements of a wxArray
559 (supposed to contain pointers).
561 RemoveAt(size_t index
, size_t count
= 1);
567 @name Searching and Sorting
572 This version of Index() is for wxArray and wxObjArray only.
574 Searches the element in the array, starting from either beginning or
575 the end depending on the value of @a searchFromEnd parameter.
576 @c wxNOT_FOUND is returned if the element is not found, otherwise the
577 index of the element is returned.
579 @note Even for wxObjArray classes, the operator "==" of the elements in
580 the array is @b not used by this function. It searches exactly
581 the given element in the array and so will only succeed if this
582 element had been previously added to the array, but fail even if
583 another, identical, element is in the array.
585 int Index(T
& item
, bool searchFromEnd
= false) const;
587 This version of Index() is for wxSortedArray only.
589 Searches the element in the array, starting from either beginning or
590 the end depending on the value of @a searchFromEnd parameter.
591 @c wxNOT_FOUND is returned if the element is not found, otherwise the
592 index of the element is returned.
594 const int Index(T
& item
) const;
597 Search for a place to insert @a item into the sorted array (binary
598 search). The index returned is just before the first existing item that
599 is greater or equal (according to the compare function) to the given
602 You have to do extra work to know if the @a item already exists in
605 This function is useful in conjunction with AddAt() for a common
606 operation of "insert only if not found".
608 size_t IndexForInsert(T item
) const;
611 The notation @c "CMPFUNCT<T>" should be read as if we had the following
615 template int CMPFUNC(T *first, T *second);
618 Where @e T is the type of the array elements. I.e. it is a function
619 returning @e int which is passed two arguments of type @e T*.
621 Sorts the array using the specified compare function: this function
622 should return a negative, zero or positive value according to whether
623 the first element passed to it is less than, equal to or greater than
626 wxSortedArray doesn't have this function because it is always sorted.
628 void Sort(CMPFUNC
<T
> compareFunction
);
635 This macro may be used to append all elements of the @a wxArray_arrayToBeAppended
636 array to the @a wxArray_arrayToModify. The two arrays must be of the same type.
638 #define WX_APPEND_ARRAY(wxArray_arrayToModify, wxArray_arrayToBeAppended)
641 This macro may be used to delete all elements of the array before emptying
642 it. It can not be used with wxObjArrays - but they will delete their
643 elements anyway when you call Empty().
645 #define WX_CLEAR_ARRAY(wxArray_arrayToBeCleared)
649 This macro declares a new object array class named @a name and containing
650 the elements of type @e T.
652 An exported array is used when compiling wxWidgets as a DLL under Windows
653 and the array needs to be visible outside the DLL. An user exported array
654 needed for exporting an array from a user DLL.
660 WX_DECLARE_OBJARRAY(MyClass, wxArrayOfMyClass); // note: not "MyClass *"!
663 You must use WX_DEFINE_OBJARRAY() macro to define the array class,
664 otherwise you would get link errors.
666 #define WX_DECLARE_OBJARRAY(T, name)
667 #define WX_DECLARE_EXPORTED_OBJARRAY(T, name)
668 #define WX_DECLARE_USER_EXPORTED_OBJARRAY(T, name)
673 This macro defines a new array class named @a name and containing the
674 elements of type @a T.
676 An exported array is used when compiling wxWidgets as a DLL under Windows
677 and the array needs to be visible outside the DLL. An user exported array
678 needed for exporting an array from a user DLL.
683 WX_DEFINE_ARRAY_INT(int, MyArrayInt);
686 WX_DEFINE_ARRAY(MyClass *, ArrayOfMyClass);
689 Note that wxWidgets predefines the following standard array classes:
690 @b wxArrayInt, @b wxArrayLong, @b wxArrayShort, @b wxArrayDouble,
693 #define WX_DEFINE_ARRAY(T, name)
694 #define WX_DEFINE_EXPORTED_ARRAY(T, name)
695 #define WX_DEFINE_USER_EXPORTED_ARRAY(T, name, exportspec)
700 This macro defines the methods of the array class @a name not defined by
701 the WX_DECLARE_OBJARRAY() macro. You must include the file
702 @<wx/arrimpl.cpp@> before using this macro and you must have the full
703 declaration of the class of array elements in scope! If you forget to do
704 the first, the error will be caught by the compiler, but, unfortunately,
705 many compilers will not give any warnings if you forget to do the second -
706 but the objects of the class will not be copied correctly and their real
707 destructor will not be called.
709 An exported array is used when compiling wxWidgets as a DLL under Windows
710 and the array needs to be visible outside the DLL. An user exported array
711 needed for exporting an array from a user DLL.
716 // first declare the class!
720 MyClass(const MyClass&);
727 #include <wx/arrimpl.cpp>
728 WX_DEFINE_OBJARRAY(wxArrayOfMyClass);
731 #define WX_DEFINE_OBJARRAY(name)
732 #define WX_DEFINE_EXPORTED_OBJARRAY(name)
733 #define WX_DEFINE_USER_EXPORTED_OBJARRAY(name)
738 This macro defines a new sorted array class named @a name and containing
739 the elements of type @e T.
741 An exported array is used when compiling wxWidgets as a DLL under Windows
742 and the array needs to be visible outside the DLL. An user exported array
743 needed for exporting an array from a user DLL.
748 WX_DEFINE_SORTED_ARRAY_INT(int, MySortedArrayInt);
751 WX_DEFINE_SORTED_ARRAY(MyClass *, ArrayOfMyClass);
754 You will have to initialize the objects of this class by passing a
755 comparison function to the array object constructor like this:
758 int CompareInts(int n1, int n2)
763 MySortedArrayInt sorted(CompareInts);
765 int CompareMyClassObjects(MyClass *item1, MyClass *item2)
767 // sort the items by their address...
768 return Stricmp(item1->GetAddress(), item2->GetAddress());
771 ArrayOfMyClass another(CompareMyClassObjects);
774 #define WX_DEFINE_SORTED_ARRAY(T, name)
775 #define WX_DEFINE_SORTED_EXPORTED_ARRAY(T, name)
776 #define WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(T, name)
780 This macro may be used to prepend all elements of the @a wxArray_arrayToBePrepended
781 array to the @a wxArray_arrayToModify. The two arrays must be of the same type.
783 #define WX_PREPEND_ARRAY(wxArray_arrayToModify, wxArray_arrayToBePrepended)