The class member function of CArray and the use method explain __ function

Source: Internet
Author: User
Tags data structures int size

CArray Foundation

C + + does not support dynamic arrays, and MFC provides a CArray class to implement the functionality of a dynamic array. Effective use of the CArray class, can improve the efficiency of the program. MFC provides a set of template libraries to implement some of the more common data structures such as ARRAY,LIST,MAP. CArray is one of them, used to implement the function of the dynamic array.

Constructors for CArray classes

CArray is derived from CObject, has two template parameters, the first argument is the variable type of the CArray class array element, and the latter is the parameter type when the function is called. If you have a class object that defines a dynamic array of Object, you can use the following two methods:

Carray<object,object> Var1;

Carray<object,object&> Var2;

The efficiency of VAR2 is high. Examples are as follows:

CArray <CPoint,CPoint&> M_array;

The statement defines a CArray array object, the template class CArray has two parameters, the first parameter is the type of the array element, in the case of CPoint, that is, M_array is a cpoint array, and the second is a reference type, and there are generally two choices, one with the same choice as the first parameter type, It means that the array object is passed as a parameter when it is passed. The second option is a reference to the first parameter type, which means that the array object passes as a parameter, passing a pointer to the object. Therefore, especially for the more complex array structure types, it is recommended to use reference passing to save memory while speeding up the program, just as this example uses cpoint&.

Second, CArray class member function

1. Property
GetSize () Gets the number of elements in this array
GetUpperBound () returns the maximum valid index value
SetSize () Sets the number of elements contained in this array

2. Operation
FreeExtra () Frees unused memory that is greater than the current upper bound
RemoveAll () Remove all elements from this array

3. Element access
GetAt () returns the value at the given index
SetAt () Sets the value of a given index; array does not allow expansion
ElementAt () returns a temporary reference to the element pointer in an array
GetData () allows elements in an array to be accessed. can be null

4. Extended Array
Setatgrow () Sets the value for a given index; If necessary, extend the array
Add () Adds an element at the end of the array, and if necessary, extends the array
Append () attaches another array on the array; If necessary, extend the array
Copy () copies the other array to the array, and if necessary, extend the array

5. Insert/Remove
InsertAt () Inserts an element (or all elements in another array) on the specified index
RemoveAt () removes an element from the specified index

6. Operator
[] Set or get elements on a specific index

Iii. examples of CArray class use
1. A good principle of use:

Before using an array, use SetSize to establish its size and allocate memory for it. If you do not use setsize, adding elements to an array causes frequent reallocation and copying. Frequent reallocation and copying is not only inefficient, but also leads to memory fragmentation.

2. Examples of the use of ADD () and SetSize ()

[CPP] view plain copy CArray <CPoint,CPoint&> M_array;    M_array.setsize (10,10);          CPoint pt1 (10,10);    M_array.add (PT1);          CPoint pt2 (10,50);    M_array.add (PT2);          CPoint PT3 (10,100);    M_array.add (PT3); int size=m_array.getsize ();

The SetSize () function sets the size of the array, which has two parameters,

(1) The first parameter sets the size of the array;

(2) The second parameter sets the size of the memory allocation when the array grows, the default value is-1, and the default value is used to ensure that the memory is allocated more rationally.

The second argument in this example is 10, meaning that adding an array element allocates 10 of the element size memory for the array to use.

You can set the size of an array at any time by using the SetSize function, and if the first parameter value is less than the number of existing members in the array, the member more than the first parameter value is truncated and the corresponding memory is freed.

Again: Before using the CArray array, it is a good idea to use SetSize to determine its size and to request storage space. If you do not, adding elements to an array requires constantly moving and copying elements that cause inefficiencies and memory fragments to run.

3. Setatgrow () and SetAt () functions

Setatgrow has two parameters, the first parameter determines the ordinal value of the array element, and the second parameter is the value of the element. This function sets the value of the corresponding array element according to the ordinal value, the function is similar to SetAt, the difference is that when the function is used to set the element value, the array automatically grows if the ordinal value is greater than the upper bound of the array. Examples are as follows:

[CPP] view plain copy carray<cstring,cstring&> m_string;   CString Sztiger ("Tiger");   CString szbear ("Bear");   CString Szdog ("dog"); M_string.   Setatgrow (0,sztiger); M_string.   Setatgrow (2,szdog); M_string.   InsertAt (1,szbear); int count=m_string. GetSize ();

Compiled to run the program, the attentive reader you may see, the output results are as follows:

The first line of characters is "Tiger" and the second line is "Bear", as we expected, but the third line is empty, and line fourth is "dog". How are the empty strings created? Fine analysis of the following three lines of code to know:

M_string. Setatgrow (0,sztiger);

M_string. Setatgrow (2,szdog);

M_string. InsertAt (1,szbear);

The first line set element 0 to "Tiger", which is not in doubt.

The second line sets element 2 to "dog", but automatically fills the element 1 as an empty string while setting element 2.

The third line inserts "Bear" as element 1, while the original element 1 and element 2 move back to element 2 and element 3.

How about, this time understand it.

4. RemoveAt () and InsertAt () functions

The InsertAt function inserts the corresponding element at the specified ordinal number, and the element behind the insertion point automatically moves backwards during execution.

RemoveAt has only one parameter, the element ordinal value. The function deletes the corresponding element value based on the element ordinal value, and the following elements are automatically moved forward.

Finally, one point: the Removeat,insertat function operation will cause the array elements to shift, the running time is greater than the Setat,removeall,add function.

CArray Use detailed

MFC's array classes support arrays that are similar to regular arrays and can hold any data type. A regular array must be defined before it can be used to accommodate all the elements that may be required. That is, the size is determined first, and the objects created by the MFC array class can be dynamically increased or reduced as needed, and the initial subscript of the array is 0, and the upper limit can be fixed or increased as the element increases. The address of an array in memory is still continuously allocated.
MFC defines the array template class CArray and defines Cbytearray,carray,cuintarray,cdarray,cstringarray,cobarray,cptrarray for a variety of commonly used variable types. See table below: Array class
Variable type
Range of variable values
Header file

CArray
To set various types through the parameter types of the template class
Afxtempl.h

CByteArray
8-bit unsigned integer byte type
0-255
Afxcoll.h

CArray
16-bit unsigned integer word type
0-65535
Afxcoll.h

Cdarray
32-bit unsigned integer DWORD type
0-4294967295
Afxcoll.h

CUIntArray
32-bit unsigned integer UINT type
0-4294967295
Afxcoll.h

CStringArray
CString string String
Afxcoll.h

CObArray
CObject class and its derived classes
Afxcoll.h

CPtrArray
void* Type pointer
Afxcoll.h


MFC array classes Use the same method, and the following example demonstrates how to use the array class, respectively, in CArray and CUIntArray.

Use CArray to open VC + + 6.0 to create a project array based on the dialog box. Add a statement to the Carraydlg class declaration file (ArrayDlg.h):

#include <afxtempl.h>

Keep in mind: Use CArray must include header file afxtempl.h.

Open the main dialog resource Idd_array_dialog, add a button Idc_array_cpoint, the caption is Carray_cpoint, double-click the button, and add the following code to the Onarraycpoint () function:

[CPP]  View plain  copy void carraydlg::onarraycpoint ()    {           CArray <CPoint,CPoint&> m_Array;             m_array.setsize (10,10);           &NBSP;&NBSP;&NBSP;CPOINT&NBSP;PT1 (10,10);       m_array.add (PT1);           cpoint pt2 (10,50);          m_array.add (PT2);          cpoint pt3 (10,100);         m_array.add (PT3);          int  size=m_array.getsize ();     &NBSP;&NBSP;&NBSP;&NBSP;CCLIENTDC&NBSP;DC (this);     &NBSP;&NBSP;&NBSP;&NBSP;DC. MoveTo (0,0);            cpoint pt;    

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.