Corrected some typos.
[wxWidgets.git] / docs / latex / wx / array.tex
1 \section{\class{wxArray}}\label{wxarray}
2
3 This section describes the so called {\it dynamic arrays}. This is a C
4 array-like data structure i.e. the member access time is constant (and not
5 linear in number of container elements as for linked lists). However, these
6 arrays are dynamic in the sense that they will automatically allocate more
7 memory if there is not enough of it for adding a new element. They also perform
8 range checking on the index values but in debug mode only, so please be sure to
9 compile your application in debug mode to use it (see \helpref{debugging overview}{debuggingoverview} for
10 details). So, unlike the arrays in some other
11 languages, attempt to access an element beyond the arrays bound doesn't
12 automatically expand the array but provokes an assertion failure instead in
13 debug build and does nothing (except possibly crashing your program) in the
14 release build.
15
16 The array classes were designed to be reasonably efficient, both in terms of
17 run-time speed and memory consumption and the executable size. The speed of
18 array item access if, of course, constant (independent of number of elements)
19 making them much more efficient than linked lists (\helpref{wxList}{wxlist}).
20 Adding items to the arrays is also implemented in more or less constant time -
21 but the price is preallocating the memory in advance. In the \helpref{memory management}{wxarraymemorymanagement} section
22 you may find some useful hints about optimizing wxArray memory usage. As for executable size, all
23 wxArray functions are inline, so they do not take {\it any space at all}.
24
25 wxWindows has three different kinds of array. All of them derive from
26 wxBaseArray class which works with untyped data and can not be used directly.
27 The standard macros WX\_DEFINE\_ARRAY(), WX\_DEFINE\_SORTED\_ARRAY() and
28 WX\_DEFINE\_OBJARRAY() are used to define a new class deriving from it. The
29 classes declared will be called in this documentation wxArray, wxSortedArray and
30 wxObjArray but you should keep in mind that no classes with such names actually
31 exist, each time you use one of WX\_DEFINE\_XXXARRAY macro you define a class
32 with a new name. In fact, these names are "template" names and each usage of one
33 of the macros mentioned above creates a template specialization for the given
34 element type.
35
36 wxArray is suitable for storing integer types and pointers which it does not
37 treat as objects in any way, i.e. the element pointed to by the pointer is not
38 deleted when the element is removed from the array \&c. It should be noted that
39 all of wxArray functions are inline, so it costs strictly nothing to define as
40 many array types as you want (either in terms of the executable size or the
41 speed) as long as at least one of them is defined and this is always the case
42 because wxArrays are used by wxWindows internally.
43
44 wxSortedArray is a wxArray variant which should be used when searching in the
45 array is a frequently used operation. It requires you to define an additional
46 function for comparing two elements of the array element type and always stores
47 its items in the sorted order (according to this function). Thus, it's
48 \helpref{Index()}{wxarrayindex} function execution time is $O(log(N))$ instead of
49 $O(N)$ for the usual arrays but the \helpref{Add()}{wxarrayadd} method is
50 slower: it is $O(log(N))$ instead of constant time (neglecting time spent in
51 memory allocation routine). However, in a usual situation elements are added to
52 an array much less often than searched inside it, so wxSortedArray may lead to
53 huge performance improvements compared to wxArray. As wxArray this array can not
54 be used
55
56 wxObjArray class treats its elements like "objects". It may delete them when
57 they are removed from the array (invoking the correct destructor) and copies
58 them using the objects copy constructor. In order to implement this behaviour
59 the definition of the wxObjArray arrays is split in two parts: first, you should
60 declare the new wxObjArray class using WX\_DECLARE\_OBJARRAY() macro and then
61 you must include the file defining the implementation of template type:
62 <wx/arrimpl.cpp> and define the array class with WX\_DEFINE\_OBJARRAY() macro
63 from a point where the full (as opposed to `forward') declaration of the array
64 elements class is in scope. As it probably sounds very complicated here is an
65 example:
66
67 \begin{verbatim}
68 #include <wx/dynarray.h>
69
70 // we must forward declare the array because it's used inside the class
71 // declaration
72 class MyDirectory;
73 class MyFile;
74
75 // this defines two new types: ArrayOfDirectories and ArrayOfFiles which can be
76 // now used as shown below
77 WX_DECLARE_OBJARRAY(MyDirectory, ArrayOfDirectories);
78 WX_DECLARE_OBJARRAY(MyFile, ArrayOfFiles);
79
80 class MyDirectory
81 {
82 ...
83 ArrayOfDirectories m_subdirectories; // all subdirectories
84 ArrayOfFiles m_files; // all files in this directory
85 };
86
87 ...
88
89 // now that we have MyDirectory declaration in scope we may finish the
90 // definition of ArrayOfDirectories
91 #include <wx/arrimpl.cpp> // this is a magic incantation which must be done!
92 WX_DEFINE_OBJARRAY(ArrayOfDirectories);
93
94 // that's all!
95
96 \end{verbatim}
97
98 It is not as elegant as writing
99
100 \begin{verbatim}
101 typedef std::vector<MyDirectory> ArrayOfDirectories;
102 \end{verbatim}
103
104 but is not that complicated and allows the code to be compiled with any, however
105 dumb, C++ compiler in the world.
106
107 The things are much simpler for wxArray and wxSortedArray however: it is enough
108 just to write
109
110 \begin{verbatim}
111 WX_DEFINE_ARRAY(MyDirectory *, ArrayOfDirectories);
112 WX_DEFINE_SORTED_ARRAY(MyFile *, ArrayOfFiles);
113 \end{verbatim}
114
115 \wxheading{See also:}
116
117 \helpref{Container classes overview}{wxcontaineroverview}, \helpref{wxList}{wxlist}
118
119 \wxheading{Required headers:}
120
121 <wx/dynarray.h> for wxArray and wxSortedArray and additionally <wx/arrimpl.cpp>
122 for wxObjArray.
123
124 \latexignore{\rtfignore{\wxheading{Function groups}}}
125
126 \membersection{Macros for template array definition}
127
128 To use an array you must first define the array class. This is done with the
129 help of the macros in this section. The class of array elements must be (at
130 least) forward declared for WX\_DEFINE\_ARRAY, WX\_DEFINE\_SORTED\_ARRAY and
131 WX\_DECLARE\_OBJARRAY macros and must be fully declared before you use
132 WX\_DEFINE\_OBJARRAY macro.
133
134 \helpref{WX\_DEFINE\_ARRAY}{wxdefinearray}\\
135 \helpref{WX\_DEFINE\_SORTED\_ARRAY}{wxdefinesortedarray}\\
136 \helpref{WX\_DECLARE\_OBJARRAY}{wxdeclareobjarray}\\
137 \helpref{WX\_DEFINE\_OBJARRAY}{wxdefineobjarray}
138
139 \membersection{Constructors and destructors}
140
141 Array classes are 100\% C++ objects and as such they have the appropriate copy
142 constructors and assignment operators. Copying wxArray just copies the elements
143 but copying wxObjArray copies the arrays items. However, for memory-efficiency
144 sake, neither of these classes has virtual destructor. It is not very important
145 for wxArray which has trivial destructor anyhow, but it does mean that you
146 should avoid deleting wxObjArray through a wxBaseArray pointer (as you would
147 never use wxBaseArray anyhow it shouldn't be a problem) and that you should not
148 derive your own classes from the array classes.
149
150 \helpref{wxArray default constructor}{wxarrayctordef}\\
151 \helpref{wxArray copy constructors and assignment operators}{wxarrayctorcopy}\\
152 \helpref{\destruct{wxArray}}{wxarraydtor}
153
154 \membersection{Memory management}\label{wxarraymemorymanagement}
155
156 Automatic array memory management is quite trivial: the array starts by
157 preallocating some minimal amount of memory (defined by
158 WX\_ARRAY\_DEFAULT\_INITIAL\_SIZE) and when further new items exhaust already
159 allocated memory it reallocates it adding 50\% of the currently allocated
160 amount, but no more than some maximal number which is defined by
161 ARRAY\_MAXSIZE\_INCREMENT constant. Of course, this may lead to some memory
162 being wasted (ARRAY\_MAXSIZE\_INCREMENT in the worst case, i.e. 4Kb in the
163 current implementation), so the \helpref{Shrink()}{wxarrayshrink} function is
164 provided to unallocate the extra memory. The \helpref{Alloc()}{wxarrayalloc}
165 function can also be quite useful if you know in advance how many items you are
166 going to put in the array and will prevent the array code from reallocating the
167 memory more times than needed.
168
169 \helpref{Alloc}{wxarrayalloc}\\
170 \helpref{Shrink}{wxarrayshrink}
171
172 \membersection{Number of elements and simple item access}
173
174 Functions in this section return the total number of array elements and allow to
175 retrieve them - possibly using just the C array indexing $[]$ operator which
176 does exactly the same as \helpref{Item()}{wxarrayitem} method.
177
178 \helpref{Count}{wxarraycount}\\
179 \helpref{GetCount}{wxarraygetcount}\\
180 \helpref{IsEmpty}{wxarrayisempty}\\
181 \helpref{Item}{wxarrayitem}\\
182 \helpref{Last}{wxarraylast}
183
184 \membersection{Adding items}
185
186 \helpref{Add}{wxarrayadd}\\
187 \helpref{Insert}{wxarrayinsert}
188
189 \membersection{Removing items}
190
191 \helpref{WX\_CLEAR\_ARRAY}{wxcleararray}\\
192 \helpref{Empty}{wxarrayempty}\\
193 \helpref{Clear}{wxarrayclear}\\
194 \helpref{Remove}{wxarrayremove}
195
196 \membersection{Searching and sorting}
197
198 \helpref{Index}{wxarrayindex}\\
199 \helpref{Sort}{wxarraysort}
200
201 %%%%% MEMBERS HERE %%%%%
202 \helponly{\insertatlevel{2}{
203
204 \wxheading{Members}
205
206 }}
207
208 \membersection{WX\_DEFINE\_ARRAY}\label{wxdefinearray}
209
210 \func{}{WX\_DEFINE\_ARRAY}{\param{}{T}, \param{name}}
211
212 This macro defines a new array class named {\it name} and containing the
213 elements of type {\it T}. Example:
214
215 \begin{verbatim}
216 WX_DEFINE_ARRAY(int, wxArrayInt);
217
218 class MyClass;
219 WX_DEFINE_ARRAY(MyClass *, wxArrayOfMyClass);
220 \end{verbatim}
221
222 Note that wxWindows predefines the following standard array classes: wxArrayInt,
223 wxArrayLong and wxArrayPtrVoid.
224
225 \membersection{WX\_DEFINE\_SORTED\_ARRAY}\label{wxdefinesortedarray}
226
227 \func{}{WX\_DEFINE\_SORTED\_ARRAY}{\param{}{T}, \param{}{name}}
228
229 This macro defines a new sorted array class named {\it name} and containing
230 the elements of type {\it T}. Example:
231
232 \begin{verbatim}
233 WX_DEFINE_SORTED_ARRAY(int, wxArrayInt);
234
235 class MyClass;
236 WX_DEFINE_SORTED_ARRAY(MyClass *, wxArrayOfMyClass);
237 \end{verbatim}
238
239 You will have to initialize the objects of this class by passing a comparaison
240 function to the array object constructor like this:
241 \begin{verbatim}
242 int CompareInts(int n1, int n2)
243 {
244 return n1 - n2;
245 }
246
247 wxArrayInt sorted(CompareInts);
248
249 int CompareMyClassObjects(MyClass *item1, MyClass *item2)
250 {
251 // sort the items by their address...
252 return Stricmp(item1->GetAddress(), item2->GetAddress());
253 }
254
255 wxArrayOfMyClass another(CompareMyClassObjects);
256 \end{verbatim}
257
258 \membersection{WX\_DECLARE\_OBJARRAY}\label{wxdeclareobjarray}
259
260 \func{}{WX\_DECLARE\_OBJARRAY}{\param{}{T}, \param{}{name}}
261
262 This macro declares a new object array class named {\it name} and containing
263 the elements of type {\it T}. Example:
264 \begin{verbatim}
265 class MyClass;
266 WX_DEFINE_OBJARRAY(MyClass, wxArrayOfMyClass); // note: not "MyClass *"!
267 \end{verbatim}
268 You must use \helpref{WX\_DEFINE\_OBJARRAY()}{wxdefineobjarray} macro to define
269 the array class - otherwise you would get link errors.
270
271 \membersection{WX\_DEFINE\_OBJARRAY}\label{wxdefineobjarray}
272
273 \func{}{WX\_DEFINE\_OBJARRAY}{\param{}{name}}
274
275 This macro defines the methods of the array class {\it name} not defined by the
276 \helpref{WX\_DECLARE\_OBJARRAY()}{wxdeclareobjarray} macro. You must include the
277 file <wx/arrimpl.cpp> before using this macro and you must have the full
278 declaration of the class of array elements in scope! If you forget to do the
279 first, the error will be caught by the compiler, but, unfortunately, many
280 compilers will not give any warnings if you forget to do the second - but the
281 objects of the class will not be copied correctly and their real destructor will
282 not be called.
283
284 Example of usage:
285
286 \begin{verbatim}
287 // first declare the class!
288 class MyClass
289 {
290 public:
291 MyClass(const MyClass&);
292
293 ...
294
295 virtual ~MyClass();
296 };
297
298 #include <wx/arrimpl.cpp>
299 WX_DEFINE_OBJARRAY(wxArrayOfMyClass);
300 \end{verbatim}
301
302 \membersection{WX\_CLEAR\_ARRAY}\label{wxcleararray}
303
304 \func{\void}{WX\_CLEAR\_ARRAY}{\param{wxArray\& }{array}}
305
306 This macro may be used to delete all elements of the array before emptying it.
307 It can not be used with wxObjArrays - but they will delete their elements anyhow
308 when you call Empty().
309
310 \membersection{Default constructors}\label{wxarrayctor}
311
312 \func{}{wxArray}{}
313
314 \func{}{wxObjArray}{}
315
316 Default constructor initializes an empty array object.
317
318 \func{}{wxSortedArray}{\param{int (*)(T first, T second)}{compareFunction}}
319
320 There is no default constructor for wxSortedArray classes - you must initialize it
321 with a function to use for item comparaison. It is a function which is passed
322 two arguments of type {\it T} where {\it T} is the array element type and which
323 should return a negative, zero or positive value according to whether the first
324 element passed to it is less than, equal to or greater than the second one.
325
326 \membersection{wxArray copy constructor and assignemnt operator}\label{wxarrayctorcopy}
327
328 \func{}{wxArray}{\param{const wxArray\& }{array}}
329
330 \func{}{wxSortedArray}{\param{const wxSortedArray\& }{array}}
331
332 \func{}{wxObjArray}{\param{const wxObjArray\& }{array}}
333
334 \func{wxArray\&}{operator=}{\param{const wxArray\& }{array}}
335
336 \func{wxSortedArray\&}{operator=}{\param{const wxSortedArray\& }{array}}
337
338 \func{wxObjArray\&}{operator=}{\param{const wxObjArray\& }{array}}
339
340 The copy constructors and assignment operators perform a shallow array copy
341 (i.e. they don't copy the objects pointed to even if the source array contains
342 the items of pointer type) for wxArray and wxSortedArray and a deep copy (i.e.
343 the array element are copied too) for wxObjArray.
344
345 \membersection{wxArray::\destruct{wxArray}}\label{wxarraydtor}
346
347 \func{}{\destruct{wxArray}}{}
348
349 \func{}{\destruct{wxSortedArray}}{}
350
351 \func{}{\destruct{wxObjArray}}{}
352
353 The wxObjArray destructor deletes all the items owned by the array. This is not
354 done by wxArray and wxSortedArray versions - you may use
355 \helpref{WX\_CLEAR\_ARRAY}{wxcleararray} macro for this.
356
357 \membersection{wxArray::Add}\label{wxarrayadd}
358
359 \func{\void}{Add}{\param{T }{item}}
360
361 \func{\void}{Add}{\param{T *}{item}}
362
363 \func{\void}{Add}{\param{T \&}{item}}
364
365 Appends a new element to the array (where {\it T} is the type of the array
366 elements.)
367
368 The first version is used with wxArray and wxSortedArray. The second and the
369 third are used with wxObjArray. There is an {\bf important difference} between
370 them: if you give a pointer to the array, it will take ownership of it, i.e.
371 will delete it when the item is deleted from the array. If you give a reference
372 to the array, however, the array will make a copy of the item and will not take
373 ownership of the original item. Once again, it only makes sense for wxObjArrays
374 because the other array types never take ownership of their elements.
375
376 \membersection{wxArray::Alloc}\label{wxarrayalloc}
377
378 \func{\void}{Alloc}{\param{size\_t }{count}}
379
380 Preallocates memory for a given number of array elements. It is worth calling
381 when the number of items which are going to be added to the array is known in
382 advance because it will save unneeded memory reallocation. If the array already
383 has enough memory for the given number of items, nothing happens.
384
385 \membersection{wxArray::Clear}\label{wxarrayclear}
386
387 \func{\void}{Clear}{\void}
388
389 This function does the same as \helpref{Empty()}{wxarrayempty} and additionally
390 frees the memory allocated to the array.
391
392 \membersection{wxArray::Count}\label{wxarraycount}
393
394 \constfunc{size\_t}{Count}{\void}
395
396 Same as \helpref{GetCount()}{wxarraygetcount}. This function is deprecated -
397 it exists only for compatibility.
398
399 \membersection{wxObjArray::Detach}\label{wxobjarraydetach}
400
401 \func{T *}{Detach}{\param{size\_t }{index}}
402
403 Removes the element from the array, but, unlike,
404
405 \helpref{Remove()}{wxarrayremove} doesn't delete it. The function returns the
406 pointer to the removed element.
407
408 \membersection{wxArray::Empty}\label{wxarrayempty}
409
410 \func{\void}{Empty}{\void}
411
412 Empties the array. For wxObjArray classes, this destroys all of the array
413 elements. For wxArray and wxSortedArray this does nothing except marking the
414 array of being empty - this function does not free the allocated memory, use
415 \helpref{Clear()}{wxarrayclear} for this.
416
417 \membersection{wxArray::GetCount}\label{wxarraygetcount}
418
419 \constfunc{size\_t}{GetCount}{\void}
420
421 Return the number of items in the array.
422
423 \membersection{wxArray::Index}\label{wxarrayindex}
424
425 \func{int}{Index}{\param{T\& }{item}, \param{bool }{searchFromEnd = FALSE}}
426
427 \func{int}{Index}{\param{T\& }{item}}
428
429 The first version of the function is for wxArray and wxObjArray, the second is
430 for wxSortedArray only.
431
432 Searches the element in the array, starting from either beginning or the end
433 depending on the value of {\it searchFromEnd} parameter. wxNOT\_FOUND is
434 returned if the element is not found, otherwise the index of the element is
435 returned.
436
437 Linear search is used for the wxArray and wxObjArray classes but binary search
438 in the sorted array is used for wxSortedArray (this is why searchFromEnd
439 parameter doesn't make sense for it).
440
441 \membersection{wxArray::Insert}\label{wxarrayinsert}
442
443 \func{\void}{Insert}{\param{T }{item}, \param{size\_t }{n}}
444
445 \func{\void}{Insert}{\param{T *}{item}, \param{size\_t }{n}}
446
447 \func{\void}{Insert}{\param{T \&}{item}, \param{size\_t }{n}}
448
449 Insert a new item into the array before the item {\it n} - thus, {\it
450 Insert(something, 0u}} will insert an item in such way that it will become the
451 first array element.
452
453 Please see \helpref{Add()}{wxarrayadd} for explanation of the differences
454 between the overloaded versions of this function.
455
456 \membersection{wxArray::IsEmpty}\label{wxarrayisempty}
457
458 \constfunc{bool}{IsEmpty}{}
459
460 Returns TRUE if the array is empty, FALSE otherwise.
461
462 \membersection{wxArray::Item}\label{wxarrayitem}
463
464 \constfunc{T\&}{Item}{\param{size\_t }{index}}
465
466 Returns the item at the given position in the array. If {\it index} is out of
467 bounds, an assert failure is raised in the debug builds but nothing special is
468 done in the release build.
469
470 The returned value is of type "reference to the array element type" for all of
471 the array classes.
472
473 \membersection{wxArray::Last}\label{wxarraylast}
474
475 \constfunc{T\&}{Last}{\void}
476
477 Returns the last element in the array, i.e. is the same as Item(GetCount() - 1).
478 An assert failure is raised in the debug mode if the array is empty.
479
480 The returned value is of type "reference to the array element type" for all of
481 the array classes.
482
483 \membersection{wxArray::Remove}\label{wxarrayremove}
484
485 \func{\void}{Remove}{\param{size\_t }{index}}
486
487 \func{\void}{Remove}{\param{T }{item}}
488
489 Removes the element from the array either by index or by value. When an element
490 is removed from wxObjArray it is deleted by the array - use
491 \helpref{Detach()}{wxobjarraydetach} if you don't want this to happen. On the
492 other hand, when an object is removed from a wxArray nothing happens - you
493 should delete the it manually if required:
494
495 \begin{verbatim}
496 T *item = array[n];
497 delete item;
498 array.Remove(n)
499 \end{verbatim}
500
501 See also \helpref{WX\_CLEAR\_ARRAY}{wxcleararray} macro which deletes all
502 elements of a wxArray (supposed to contain pointers).
503
504 \membersection{wxArray::Shrink}\label{wxarrayshrink}
505
506 \func{\void}{Shrink}{\void}
507
508 Frees all memory unused by the array. If the program knows that no new items
509 will be added to the array it may call Shrink() to reduce its memory usage.
510 However, if a new item is added to the array, some extra memory will be
511 allocated again.
512
513 \membersection{wxArray::Sort}\label{wxarraysort}
514
515 \func{\void}{Sort}{\param{CMPFUNC<T> }{compareFunction}}
516
517 The notation CMPFUNC<T> should be read as if we had the following declaration:
518
519 \begin{verbatim}
520 template int CMPFUNC(T *first, T *second);
521 \end{verbatim}
522
523 where {\it T} is the type of the array elements. I.e. it is a function returning
524 {\it int} which is passed two arguments of type {\it T *}.
525
526 Sorts the array using the specified compare function: this function should
527 return a negative, zero or positive value according to whether the first element
528 passed to it is less than, equal to or greater than the second one.
529
530 wxSortedArray doesn't have this function because it is always sorted.
531