📄 array.tex
字号:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Name: array.tex%% Purpose: wxArray%% Author: wxWidgets Team%% Modified by:%% Created:%% RCS-ID: $Id: array.tex,v 1.40 2006/11/04 12:42:03 VZ Exp $%% Copyright: (c) wxWidgets Team%% License: wxWindows license%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\section{\class{wxArray}}\label{wxarray}This section describes the so called {\it dynamic arrays}. This is a Carray-like data structure i.e. the member access time is constant (and notlinear according to the number of container elements as for linked lists). However, thesearrays are dynamic in the sense that they will automatically allocate morememory if there is not enough of it for adding a new element. They also performrange checking on the index values but in debug mode only, so please be sure tocompile your application in debug mode to use it (see \helpref{debugging overview}{debuggingoverview} fordetails). So, unlike the arrays in some otherlanguages, attempt to access an element beyond the arrays bound doesn'tautomatically expand the array but provokes an assertion failure instead indebug build and does nothing (except possibly crashing your program) in therelease build.The array classes were designed to be reasonably efficient, both in terms ofrun-time speed and memory consumption and the executable size. The speed ofarray item access is, of course, constant (independent of the number of elements)making them much more efficient than linked lists (\helpref{wxList}{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 \helpref{memory management}{wxarraymemorymanagement} sectionyou may find some useful hints about optimizing wxArray memory usage. As for executable size, allwxArray functions are inline, so they do not take {\it any space at all}.wxWidgets has three different kinds of array. All of them derive fromwxBaseArray class which works with untyped data and can not be used directly.The standard macros WX\_DEFINE\_ARRAY(), WX\_DEFINE\_SORTED\_ARRAY() andWX\_DEFINE\_OBJARRAY() are used to define a new class deriving from it. Theclasses declared will be called in this documentation wxArray, wxSortedArray andwxObjArray but you should keep in mind that no classes with such names actuallyexist, each time you use one of WX\_DEFINE\_XXXARRAY macro you define a classwith a new name. In fact, these names are "template" names and each usage of oneof the macros mentioned above creates a template specialization for the givenelement type.wxArray is suitable for storing integer types and pointers which it does nottreat as objects in any way, i.e. the element pointed to by the pointer is notdeleted when the element is removed from the array. It should be noted thatall of wxArray's functions are inline, so it costs strictly nothing to define asmany array types as you want (either in terms of the executable size or thespeed) as long as at least one of them is defined and this is always the casebecause wxArrays are used by wxWidgets internally. This class has one seriouslimitation: it can only be used for storing integral types (bool, char, short,int, long and their unsigned variants) or pointers (of any kind). An attemptto use with objects of sizeof() greater than sizeof(long) will provoke aruntime assertion failure, however declaring a wxArray of floats will not (onthe machines where sizeof(float) <= sizeof(long)), yet it will {\bf not} work,please use wxObjArray for storing floats and doubles (NB: a more efficientwxArrayDouble class is scheduled for the next release of wxWidgets).wxSortedArray is a wxArray variant which should be used when searching in thearray is a frequently used operation. It requires you to define an additionalfunction for comparing two elements of the array element type and always storesits items in the sorted order (according to this function). Thus, it is \helpref{Index()}{wxarrayindex} function execution time is $O(log(N))$ instead of$O(N)$ for the usual arrays but the \helpref{Add()}{wxarrayadd} method isslower: it is $O(log(N))$ instead of constant time (neglecting time spent inmemory allocation routine). However, in a usual situation elements are added toan array much less often than searched inside it, so wxSortedArray may lead tohuge performance improvements compared to wxArray. Finally, it should benoticed that, as wxArray, wxSortedArray can be only used for storing integraltypes or pointers.wxObjArray class treats its elements like "objects". It may delete them whenthey are removed from the array (invoking the correct destructor) and copiesthem using the objects copy constructor. In order to implement this behaviourthe definition of the wxObjArray arrays is split in two parts: first, you shoulddeclare the new wxObjArray class using WX\_DECLARE\_OBJARRAY() macro and thenyou must include the file defining the implementation of template type:<wx/arrimpl.cpp> and define the array class with WX\_DEFINE\_OBJARRAY() macrofrom a point where the full (as opposed to `forward') declaration of the arrayelements class is in scope. As it probably sounds very complicated here is anexample:\begin{verbatim}#include <wx/dynarray.h>// we must forward declare the array because it is used inside the class// declarationclass MyDirectory;class MyFile;// this defines two new types: ArrayOfDirectories and ArrayOfFiles which can be// now used as shown belowWX_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!\end{verbatim}It is not as elegant as writing\begin{verbatim}typedef std::vector<MyDirectory> ArrayOfDirectories;\end{verbatim}but is not that complicated and allows the code to be compiled with any, howeverdumb, C++ compiler in the world.Things are much simpler for wxArray and wxSortedArray however: it is enoughjust to write\begin{verbatim}WX_DEFINE_ARRAY_INT(int, ArrayOfInts);WX_DEFINE_SORTED_ARRAY_INT(int, ArrayOfSortedInts);\end{verbatim}i.e. there is only one {\tt DEFINE} macro and no need for separate{\tt DECLARE} one. For the arrays of the primitive types, the macros {\tt WX\_DEFINE\_ARRAY\_CHAR/SHORT/INT/SIZE\_T/LONG/DOUBLE} should be useddepending on the sizeof of the values (notice that storing values of smallertype, e.g. shorts, in an array of larger one, e.g. {\tt ARRAY\_INT}, does\emph{not} work on all architectures!).\wxheading{See also:}\helpref{Container classes overview}{wxcontaineroverview}, \helpref{wxList}{wxlist}\wxheading{Include files}<wx/dynarray.h> for wxArray and wxSortedArray and additionally <wx/arrimpl.cpp>for wxObjArray.\latexignore{\rtfignore{\wxheading{Function groups}}}\membersection{Macros for template array definition}\label{arraymacros}To use an array you must first define the array class. This is done with thehelp of the macros in this section. The class of array elements must be (atleast) forward declared for WX\_DEFINE\_ARRAY, WX\_DEFINE\_SORTED\_ARRAY andWX\_DECLARE\_OBJARRAY macros and must be fully declared before you useWX\_DEFINE\_OBJARRAY macro.\helpref{WX\_DEFINE\_ARRAY}{wxdefinearray}\\\helpref{WX\_DEFINE\_EXPORTED\_ARRAY}{wxdefinearray}\\\helpref{WX\_DEFINE\_USER\_EXPORTED\_ARRAY}{wxdefinearray}\\\helpref{WX\_DEFINE\_SORTED\_ARRAY}{wxdefinesortedarray}\\\helpref{WX\_DEFINE\_SORTED\_EXPORTED\_ARRAY}{wxdefinesortedarray}\\\helpref{WX\_DEFINE\_SORTED\_USER\_EXPORTED\_ARRAY}{wxdefinesortedarray}\\\helpref{WX\_DECLARE\_EXPORTED\_OBJARRAY}{wxdeclareobjarray}\\\helpref{WX\_DECLARE\_USER\_EXPORTED\_OBJARRAY}{wxdeclareobjarray}\\\helpref{WX\_DEFINE\_OBJARRAY}{wxdefineobjarray}\\\helpref{WX\_DEFINE\_EXPORTED\_OBJARRAY}{wxdefineobjarray}\\\helpref{WX\_DEFINE\_USER\_EXPORTED\_OBJARRAY}{wxdefineobjarray}To slightly complicate the matters even further, the operator $->$ defined bydefault for the array iterators by these macros only makes sense if the arrayelement type is not a pointer itself and, although it still works, thisprovokes warnings from some compilers and to avoid them you should use the{\tt \_PTR} versions of the macros above. For example, to define an array ofpointers to {\tt double} you should use:\begin{verbatim}WX_DEFINE_ARRAY_PTR(double *, MyArrayOfDoublePointers);\end{verbatim}Note that the above macros are generally only useful forwxObject types. There are separate macros for declaring an array of a simple type,such as an int.The following simple types are supported:\\int\\long\\size\_t\\doubleTo create an array of a simple type, simply append the type you want in CAPS tothe array definition.For example, for an integer array, you'd use one of the following variants:\helpref{WX\_DEFINE\_ARRAY\_INT}{wxdefinearray}\\\helpref{WX\_DEFINE\_EXPORTED\_ARRAY\_INT}{wxdefinearray}\\\helpref{WX\_DEFINE\_USER\_EXPORTED\_ARRAY\_INT}{wxdefinearray}\\\helpref{WX\_DEFINE\_SORTED\_ARRAY\_INT}{wxdefinesortedarray}\\\helpref{WX\_DEFINE\_SORTED\_EXPORTED\_ARRAY\_INT}{wxdefinesortedarray}\\\helpref{WX\_DEFINE\_SORTED\_USER\_EXPORTED\_ARRAY\_INT}{wxdefinesortedarray}\\\membersection{Constructors and destructors}\label{arrayconstructorsdestructors}Array classes are 100\% C++ objects and as such they have the appropriate copyconstructors and assignment operators. Copying wxArray just copies the elementsbut copying wxObjArray copies the arrays items. However, for memory-efficiencysake, neither of these classes has virtual destructor. It is not very importantfor wxArray which has trivial destructor anyhow, but it does mean that youshould avoid deleting wxObjArray through a wxBaseArray pointer (as you wouldnever use wxBaseArray anyhow it shouldn't be a problem) and that you should notderive your own classes from the array classes.\helpref{wxArray default constructor}{wxarrayctordef}\\\helpref{wxArray copy constructors and assignment operators}{wxarrayctorcopy}\\\helpref{\destruct{wxArray}}{wxarraydtor}\membersection{Memory management}\label{wxarraymemorymanagement}Automatic array memory management is quite trivial: the array starts bypreallocating some minimal amount of memory (defined byWX\_ARRAY\_DEFAULT\_INITIAL\_SIZE) and when further new items exhaust alreadyallocated memory it reallocates it adding 50\% of the currently allocatedamount, but no more than some maximal number which is defined byARRAY\_MAXSIZE\_INCREMENT constant. Of course, this may lead to some memorybeing wasted (ARRAY\_MAXSIZE\_INCREMENT in the worst case, i.e. 4Kb in thecurrent implementation), so the \helpref{Shrink()}{wxarrayshrink} function isprovided to deallocate the extra memory. The \helpref{Alloc()}{wxarrayalloc}function can also be quite useful if you know in advance how many items you aregoing to put in the array and will prevent the array code from reallocating thememory more times than needed.\helpref{Alloc}{wxarrayalloc}\\\helpref{Shrink}{wxarrayshrink}\membersection{Number of elements and simple item access}\label{arrayelementsaccess}Functions in this section return the total number of array elements and allow toretrieve them - possibly using just the C array indexing $[]$ operator whichdoes exactly the same as \helpref{Item()}{wxarrayitem} method.\helpref{Count}{wxarraycount}\\\helpref{GetCount}{wxarraygetcount}\\\helpref{IsEmpty}{wxarrayisempty}\\\helpref{Item}{wxarrayitem}\\\helpref{Last}{wxarraylast}\membersection{Adding items}\label{arrayadding}\helpref{Add}{wxarrayadd}\\\helpref{Insert}{wxarrayinsert}\\\helpref{SetCount}{wxarraysetcount}\\\helpref{WX\_APPEND\_ARRAY}{wxappendarray}\\\helpref{WX\_PREPEND\_ARRAY}{wxprependarray}\membersection{Removing items}\label{arrayremoving}\helpref{WX\_CLEAR\_ARRAY}{wxcleararray}\\\helpref{Empty}{wxarrayempty}\\\helpref{Clear}{wxarrayclear}\\\helpref{RemoveAt}{wxarrayremoveat}\\\helpref{Remove}{wxarrayremove}\membersection{Searching and sorting}\label{arraysearchingandsorting}\helpref{Index}{wxarrayindex}\\\helpref{Sort}{wxarraysort}%%%%% MEMBERS HERE %%%%%\helponly{\insertatlevel{2}{\wxheading{Members}}}\membersection{WX\_DEFINE\_ARRAY}\label{wxdefinearray}\func{}{WX\_DEFINE\_ARRAY}{\param{}{T}, \param{}{name}}\func{}{WX\_DEFINE\_EXPORTED\_ARRAY}{\param{}{T}, \param{}{name}}\func{}{WX\_DEFINE\_USER\_EXPORTED\_ARRAY}{\param{}{T}, \param{}{name}, \param{}{exportspec}}This macro defines a new array class named {\it name} and containing theelements of type {\it T}. The second form is used when compiling wxWidgets asa DLL under Windows and array needs to be visible outside the DLL. The third isneeded for exporting an array from a user DLL.Example:\begin{verbatim}WX_DEFINE_ARRAY_INT(int, MyArrayInt);class MyClass;WX_DEFINE_ARRAY(MyClass *, ArrayOfMyClass);\end{verbatim}Note that wxWidgets predefines the following standard array classes: wxArrayInt,wxArrayLong and wxArrayPtrVoid.\membersection{WX\_DEFINE\_SORTED\_ARRAY}\label{wxdefinesortedarray}\func{}{WX\_DEFINE\_SORTED\_ARRAY}{\param{}{T}, \param{}{name}}\func{}{WX\_DEFINE\_SORTED\_EXPORTED\_ARRAY}{\param{}{T}, \param{}{name}}\func{}{WX\_DEFINE\_SORTED\_USER\_EXPORTED\_ARRAY}{\param{}{T}, \param{}{name}}This macro defines a new sorted array class named {\it name} and containingthe elements of type {\it T}. The second form is used when compiling wxWidgets asa DLL under Windows and array needs to be visible outside the DLL. The third isneeded for exporting an array from a user DLL.Example:\begin{verbatim}WX_DEFINE_SORTED_ARRAY_INT(int, MySortedArrayInt);class MyClass;WX_DEFINE_SORTED_ARRAY(MyClass *, ArrayOfMyClass);\end{verbatim}You will have to initialize the objects of this class by passing a comparisonfunction to the array object constructor like this:\begin{verbatim}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);\end{verbatim}\membersection{WX\_DECLARE\_OBJARRAY}\label{wxdeclareobjarray}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -