]>
git.saurik.com Git - wxWidgets.git/blob - interface/dynarray.h
1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: interface of wxArray<T>
4 // Author: wxWidgets team
6 // Licence: wxWindows license
7 /////////////////////////////////////////////////////////////////////////////
12 This section describes the so called @e dynamic arrays. This is a C
13 array-like type safe data structure i.e. the member access time is constant
15 linear according to the number of container elements as for linked lists).
17 arrays are dynamic in the sense that they will automatically allocate more
18 memory if there is not enough of it for adding a new element. They also perform
19 range checking on the index values but in debug mode only, so please be sure to
20 compile your application in debug mode to use it (see @ref
21 overview_debuggingoverview "debugging overview" for
22 details). So, unlike the arrays in some other
23 languages, attempt to access an element beyond the arrays bound doesn't
24 automatically expand the array but provokes an assertion failure instead in
25 debug build and does nothing (except possibly crashing your program) in the
28 The array classes were designed to be reasonably efficient, both in terms of
29 run-time speed and memory consumption and the executable size. The speed of
30 array item access is, of course, constant (independent of the number of
32 making them much more efficient than linked lists (wxList).
33 Adding items to the arrays is also implemented in more or less constant time -
34 but the price is preallocating the memory in advance. In the @ref
35 wxArray::memorymanagement "memory management" section
36 you may find some useful hints about optimizing wxArray memory usage. As for
38 wxArray functions are inline, so they do not take @e any space at all.
40 wxWidgets has three different kinds of array. All of them derive from
41 wxBaseArray class which works with untyped data and can not be used directly.
42 The standard macros WX_DEFINE_ARRAY(), WX_DEFINE_SORTED_ARRAY() and
43 WX_DEFINE_OBJARRAY() are used to define a new class deriving from it. The
44 classes declared will be called in this documentation wxArray, wxSortedArray and
45 wxObjArray but you should keep in mind that no classes with such names actually
46 exist, each time you use one of WX_DEFINE_XXXARRAY macro you define a class
47 with a new name. In fact, these names are "template" names and each usage of one
48 of the macros mentioned above creates a template specialization for the given
51 wxArray is suitable for storing integer types and pointers which it does not
52 treat as objects in any way, i.e. the element pointed to by the pointer is not
53 deleted when the element is removed from the array. It should be noted that
54 all of wxArray's functions are inline, so it costs strictly nothing to define as
55 many array types as you want (either in terms of the executable size or the
56 speed) as long as at least one of them is defined and this is always the case
57 because wxArrays are used by wxWidgets internally. This class has one serious
58 limitation: it can only be used for storing integral types (bool, char, short,
59 int, long and their unsigned variants) or pointers (of any kind). An attempt
60 to use with objects of sizeof() greater than sizeof(long) will provoke a
61 runtime assertion failure, however declaring a wxArray of floats will not (on
62 the machines where sizeof(float) = sizeof(long)), yet it will @b not work,
63 please use wxObjArray for storing floats and doubles.
65 wxSortedArray is a wxArray variant which should be used when searching in the
66 array is a frequently used operation. It requires you to define an additional
67 function for comparing two elements of the array element type and always stores
68 its items in the sorted order (according to this function). Thus, it is
69 wxArray::Index function execution time is O(log(N)) instead of
70 O(N) for the usual arrays but the wxArray::Add method is
71 slower: it is O(log(N)) instead of constant time (neglecting time spent in
72 memory allocation routine). However, in a usual situation elements are added to
73 an array much less often than searched inside it, so wxSortedArray may lead to
74 huge performance improvements compared to wxArray. Finally, it should be
75 noticed that, as wxArray, wxSortedArray can be only used for storing integral
78 wxObjArray class treats its elements like "objects". It may delete them when
79 they are removed from the array (invoking the correct destructor) and copies
80 them using the objects copy constructor. In order to implement this behaviour
81 the definition of the wxObjArray arrays is split in two parts: first, you should
82 declare the new wxObjArray class using WX_DECLARE_OBJARRAY() macro and then
83 you must include the file defining the implementation of template type:
84 wx/arrimpl.cpp and define the array class with WX_DEFINE_OBJARRAY() macro
85 from a point where the full (as opposed to 'forward') declaration of the array
86 elements class is in scope. As it probably sounds very complicated here is an
90 #include wx/dynarray.h
92 // we must forward declare the array because it is used inside the class
97 // this defines two new types: ArrayOfDirectories and ArrayOfFiles which can be
98 // now used as shown below
99 WX_DECLARE_OBJARRAY(MyDirectory, ArrayOfDirectories);
100 WX_DECLARE_OBJARRAY(MyFile, ArrayOfFiles);
105 ArrayOfDirectories m_subdirectories; // all subdirectories
106 ArrayOfFiles m_files; // all files in this directory
111 // now that we have MyDirectory declaration in scope we may finish the
112 // definition of ArrayOfDirectories -- note that this expands into some C++
113 // code and so should only be compiled once (i.e., don't put this in the
114 // header, but into a source file or you will get linking errors)
115 #include wx/arrimpl.cpp // this is a magic incantation which must be done!
116 WX_DEFINE_OBJARRAY(ArrayOfDirectories);
121 It is not as elegant as writing
124 typedef std::vectorMyDirectory ArrayOfDirectories;
127 but is not that complicated and allows the code to be compiled with any, however
128 dumb, C++ compiler in the world.
130 Remember to include wx/arrimpl.cpp just before each WX_DEFINE_OBJARRAY
131 ocurrence in your code, even if you have several in the same file.
133 Things are much simpler for wxArray and wxSortedArray however: it is enough
137 WX_DEFINE_ARRAY_INT(int, ArrayOfInts);
138 WX_DEFINE_SORTED_ARRAY_INT(int, ArrayOfSortedInts);
141 i.e. there is only one @c DEFINE macro and no need for separate
142 @c DECLARE one. For the arrays of the primitive types, the macros
143 @c WX_DEFINE_ARRAY_CHAR/SHORT/INT/SIZE_T/LONG/DOUBLE should be used
144 depending on the sizeof of the values (notice that storing values of smaller
145 type, e.g. shorts, in an array of larger one, e.g. @c ARRAY_INT, does
146 not work on all architectures!).
151 @see @ref overview_container, wxList<T>, wxVector<T>
158 Appends the given number of @a copies of the @a item to the array
159 consisting of the elements of type @e T.
160 The first version is used with wxArray. The second is used with wxSortedArray,
161 returning the index where @a item is stored. The third and the
162 fourth ones are used with wxObjArray. There is an important difference between
163 them: if you give a pointer to the array, it will take ownership of it, i.e.
164 will delete it when the item is deleted from the array. If you give a reference
165 to the array, however, the array will make a copy of the item and will not take
166 ownership of the original item. Once again, it only makes sense for wxObjArrays
167 because the other array types never take ownership of their elements. Also note
168 that you cannot append more than one pointer as reusing it would lead to
169 deleting it twice (or more) and hence to a crash.
170 You may also use WX_APPEND_ARRAY() macro to append all
171 elements of one array to another one but it is more efficient to use
172 @a copies parameter and modify the elements in place later if you plan to
173 append a lot of items.
175 void Add(T item
, size_t copies
= 1);
178 void Add(T
& item
, size_t copies
= 1);
182 Inserts the given @a item into the array in the specified @e index
184 Be aware that you will set out the order of the array if you give a wrong
186 This function is useful in conjunction with
187 wxArray::IndexForInsert for a common operation
188 of "insert only if not found".
190 void AddAt(T item
, size_t index
);
208 Preallocates memory for a given number of array elements. It is worth calling
209 when the number of items which are going to be added to the array is known in
210 advance because it will save unneeded memory reallocation. If the array already
211 has enough memory for the given number of items, nothing happens. In any case,
212 the existing contents of the array is not modified.
214 void Alloc(size_t count
);
217 This function does the same as wxArray::Empty and additionally
218 frees the memory allocated to the array.
223 Array classes are 100% C++ objects and as such they have the appropriate copy
224 constructors and assignment operators. Copying wxArray just copies the elements
225 but copying wxObjArray copies the arrays items. However, for memory-efficiency
226 sake, neither of these classes has virtual destructor. It is not very important
227 for wxArray which has trivial destructor anyhow, but it does mean that you
228 should avoid deleting wxObjArray through a wxBaseArray pointer (as you would
229 never use wxBaseArray anyhow it shouldn't be a problem) and that you should not
230 derive your own classes from the array classes.
231 @ref wxArray::ctordef "wxArray default constructor"
233 @ref wxArray::ctorcopy "wxArray copy constructors and assignment operators"
235 @ref wxArray::dtor ~wxArray
241 (T first, T second)@e compareFunction)
242 There is no default constructor for wxSortedArray classes - you must initialize
244 with a function to use for item comparison. It is a function which is passed
245 two arguments of type @e T where @e T is the array element type and which
246 should return a negative, zero or positive value according to whether the first
247 element passed to it is less than, equal to or greater than the second one.
255 Removes the element from the array, but, unlike,
256 wxArray::Remove doesn't delete it. The function returns the
257 pointer to the removed element.
259 T
* Detach(size_t index
);
262 Empties the array. For wxObjArray classes, this destroys all of the array
263 elements. For wxArray and wxSortedArray this does nothing except marking the
264 array of being empty - this function does not free the allocated memory, use
265 wxArray::Clear for this.
270 Return the number of items in the array.
272 size_t GetCount() const;
276 The first version of the function is for wxArray and wxObjArray, the second is
277 for wxSortedArray only.
278 Searches the element in the array, starting from either beginning or the end
279 depending on the value of @a searchFromEnd parameter. @c wxNOT_FOUND is
280 returned if the element is not found, otherwise the index of the element is
282 Linear search is used for the wxArray and wxObjArray classes but binary search
283 in the sorted array is used for wxSortedArray (this is why searchFromEnd
284 parameter doesn't make sense for it).
285 @b NB: even for wxObjArray classes, the operator==() of the elements in the
286 array is @b not used by this function. It searches exactly the given
287 element in the array and so will only succeed if this element had been
288 previously added to the array, but fail even if another, identical, element is
291 int Index(T
& item
, bool searchFromEnd
= false) const;
292 const int Index(T
& item
) const;
296 Search for a place to insert @a item into the sorted array (binary search).
297 The index returned is just before the first existing item that is greater or
299 (according to the compare function) to the given @e item.
300 You have to do extra work to know if the @a item already exists in array.
301 This function is useful in conjunction with
302 wxArray::AddAt for a common operation
303 of "insert only if not found".
305 size_t IndexForInsert(T item
) const;
309 Insert the given number of @a copies of the @a item into the array before
310 the existing item @a n - thus, @e Insert(something, 0u) will insert an
311 item in such way that it will become the first array element.
312 wxSortedArray doesn't have this function because inserting in wrong place
313 would break its sorted condition.
314 Please see wxArray::Add for explanation of the differences
315 between the overloaded versions of this function.
317 void Insert(T item
, size_t n
, size_t copies
= 1);
318 void Insert(T
* item
, size_t n
);
319 void Insert(T
& item
, size_t n
, size_t copies
= 1);
323 Returns @true if the array is empty, @false otherwise.
325 bool IsEmpty() const;
328 Returns the item at the given position in the array. If @a index is out of
329 bounds, an assert failure is raised in the debug builds but nothing special is
330 done in the release build.
331 The returned value is of type "reference to the array element type" for all of
334 T
Item(size_t index
) const;
337 Returns the last element in the array, i.e. is the same as Item(GetCount() - 1).
338 An assert failure is raised in the debug mode if the array is empty.
339 The returned value is of type "reference to the array element type" for all of
345 To use an array you must first define the array class. This is done with the
346 help of the macros in this section. The class of array elements must be (at
347 least) forward declared for WX_DEFINE_ARRAY, WX_DEFINE_SORTED_ARRAY and
348 WX_DECLARE_OBJARRAY macros and must be fully declared before you use
349 WX_DEFINE_OBJARRAY macro.
352 WX_DEFINE_EXPORTED_ARRAY()
354 WX_DEFINE_USER_EXPORTED_ARRAY()
356 WX_DEFINE_SORTED_ARRAY()
358 WX_DEFINE_SORTED_EXPORTED_ARRAY()
360 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY()
362 WX_DECLARE_EXPORTED_OBJARRAY()
364 WX_DECLARE_USER_EXPORTED_OBJARRAY()
368 WX_DEFINE_EXPORTED_OBJARRAY()
370 WX_DEFINE_USER_EXPORTED_OBJARRAY()
371 To slightly complicate the matters even further, the operator - defined by
372 default for the array iterators by these macros only makes sense if the array
373 element type is not a pointer itself and, although it still works, this
374 provokes warnings from some compilers and to avoid them you should use the
375 @c _PTR versions of the macros above. For example, to define an array of
376 pointers to @c double you should use:
378 Note that the above macros are generally only useful for
379 wxObject types. There are separate macros for declaring an array of a simple
382 The following simple types are supported:
391 To create an array of a simple type, simply append the type you want in CAPS to
392 the array definition.
393 For example, for an integer array, you'd use one of the following variants:
394 WX_DEFINE_ARRAY_INT()
396 WX_DEFINE_EXPORTED_ARRAY_INT()
398 WX_DEFINE_USER_EXPORTED_ARRAY_INT()
400 WX_DEFINE_SORTED_ARRAY_INT()
402 WX_DEFINE_SORTED_EXPORTED_ARRAY_INT()
404 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY_INT()
409 Automatic array memory management is quite trivial: the array starts by
410 preallocating some minimal amount of memory (defined by
411 WX_ARRAY_DEFAULT_INITIAL_SIZE) and when further new items exhaust already
412 allocated memory it reallocates it adding 50% of the currently allocated
413 amount, but no more than some maximal number which is defined by
414 ARRAY_MAXSIZE_INCREMENT constant. Of course, this may lead to some memory
415 being wasted (ARRAY_MAXSIZE_INCREMENT in the worst case, i.e. 4Kb in the
416 current implementation), so the wxArray::Shrink function is
417 provided to deallocate the extra memory. The wxArray::Alloc
418 function can also be quite useful if you know in advance how many items you are
419 going to put in the array and will prevent the array code from reallocating the
420 memory more times than needed.
428 Functions in this section return the total number of array elements and allow to
429 retrieve them - possibly using just the C array indexing [] operator which
430 does exactly the same as wxArray::Item method.
442 Removes an element from the array by value: the first item of the
443 array equal to @a item is removed, an assert failure will result from an
444 attempt to remove an item which doesn't exist in the array.
445 When an element is removed from wxObjArray it is deleted by the array - use
446 Detach() if you don't want this to happen. On the
447 other hand, when an object is removed from a wxArray nothing happens - you
448 should delete it manually if required:
450 See also WX_CLEAR_ARRAY() macro which deletes all
451 elements of a wxArray (supposed to contain pointers).
456 Removes @a count elements starting at @a index from the array. When an
457 element is removed from wxObjArray it is deleted by the array - use
458 Detach() if you don't want this to happen. On
459 the other hand, when an object is removed from a wxArray nothing happens -
460 you should delete it manually if required:
462 See also WX_CLEAR_ARRAY() macro which deletes all
463 elements of a wxArray (supposed to contain pointers).
465 RemoveAt(size_t index
, size_t count
= 1);
483 wxArray::IndexForInsert
491 This function ensures that the number of array elements is at least
492 @e count. If the array has already @a count or more items, nothing is
493 done. Otherwise, @c count - GetCount() elements are added and initialized to
496 @see wxArray::GetCount
498 void SetCount(size_t count
);
501 Frees all memory unused by the array. If the program knows that no new items
502 will be added to the array it may call Shrink() to reduce its memory usage.
503 However, if a new item is added to the array, some extra memory will be
509 The notation CMPFUNCT should be read as if we had the following declaration:
511 where @e T is the type of the array elements. I.e. it is a function returning
512 @e int which is passed two arguments of type @e T *.
513 Sorts the array using the specified compare function: this function should
514 return a negative, zero or positive value according to whether the first element
515 passed to it is less than, equal to or greater than the second one.
516 wxSortedArray doesn't have this function because it is always sorted.
518 void Sort(CMPFUNC
<T
> compareFunction
);
522 The copy constructors and assignment operators perform a shallow array copy
523 (i.e. they don't copy the objects pointed to even if the source array contains
524 the items of pointer type) for wxArray and wxSortedArray and a deep copy (i.e.
525 the array element are copied too) for wxObjArray.
527 wxArray(const wxArray
& array
);
528 wxSortedArray(const wxSortedArray
& array
);
529 wxObjArray(const wxObjArray
& array
);
530 wxArray
operator=(const wxArray
& array
);
531 wxSortedArray
operator=(const wxSortedArray
& array
);
532 wxObjArray
operator=(const wxObjArray
& array
);
537 The wxObjArray destructor deletes all the items owned by the array. This is not
538 done by wxArray and wxSortedArray versions - you may use
539 WX_CLEAR_ARRAY() macro for this.
549 This macro may be used to append all elements of the @a other array to the
550 @e array. The two arrays must be of the same type.
552 #define WX_APPEND_ARRAY(wxArray& array, wxArray& other) /* implementation is private */
555 This macro may be used to delete all elements of the array before emptying it.
556 It can not be used with wxObjArrays - but they will delete their elements anyhow
557 when you call Empty().
559 #define WX_CLEAR_ARRAY(wxArray& array) /* implementation is private */
563 This macro declares a new object array class named @a name and containing
564 the elements of type @e T. The second form is used when compiling wxWidgets as
565 a DLL under Windows and array needs to be visible outside the DLL. The third is
566 needed for exporting an array from a user DLL.
569 You must use WX_DEFINE_OBJARRAY() macro to define
570 the array class - otherwise you would get link errors.
572 #define WX_DECLARE_OBJARRAY(T, name) /* implementation is private */
573 #define WX_DECLARE_EXPORTED_OBJARRAY(T, name) /* implementation is private */
574 #define WX_DECLARE_USER_EXPORTED_OBJARRAY(T, name) /* implementation is private */
579 This macro defines a new array class named @a name and containing the
580 elements of type @e T. The second form is used when compiling wxWidgets as
581 a DLL under Windows and array needs to be visible outside the DLL. The third is
582 needed for exporting an array from a user DLL.
585 Note that wxWidgets predefines the following standard array classes: @b
587 @b wxArrayLong, @b wxArrayShort, @b wxArrayDouble, @b wxArrayPtrVoid.
589 #define WX_DEFINE_ARRAY(T, name) /* implementation is private */
590 #define WX_DEFINE_EXPORTED_ARRAY(T, name) /* implementation is private */
591 #define WX_DEFINE_USER_EXPORTED_ARRAY(T, name, exportspec) /* implementation is private */
596 This macro defines the methods of the array class @a name not defined by the
597 WX_DECLARE_OBJARRAY() macro. You must include the
598 file wx/arrimpl.cpp before using this macro and you must have the full
599 declaration of the class of array elements in scope! If you forget to do the
600 first, the error will be caught by the compiler, but, unfortunately, many
601 compilers will not give any warnings if you forget to do the second - but the
602 objects of the class will not be copied correctly and their real destructor will
603 not be called. The latter two forms are merely aliases of the first to satisfy
604 some people's sense of symmetry when using the exported declarations.
607 #define WX_DEFINE_OBJARRAY(name) /* implementation is private */
608 #define WX_DEFINE_EXPORTED_OBJARRAY(name) /* implementation is private */
609 #define WX_DEFINE_USER_EXPORTED_OBJARRAY(name) /* implementation is private */
614 This macro defines a new sorted array class named @a name and containing
615 the elements of type @e T. The second form is used when compiling wxWidgets as
616 a DLL under Windows and array needs to be visible outside the DLL. The third is
617 needed for exporting an array from a user DLL.
620 You will have to initialize the objects of this class by passing a comparison
621 function to the array object constructor like this:
623 #define WX_DEFINE_SORTED_ARRAY(T, name) /* implementation is private */
624 #define WX_DEFINE_SORTED_EXPORTED_ARRAY(T, name) /* implementation is private */
625 #define WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(T, name) /* implementation is private */
629 This macro may be used to prepend all elements of the @a other array to the
630 @e array. The two arrays must be of the same type.
632 #define WX_PREPEND_ARRAY(wxArray& array, wxArray& other) /* implementation is private */