Array classes using MFC

Source: Internet
Author: User
Tags textout

Array classes using MFC

The arrays supported by the MFC array class are similar to the regular arrays in C ++ and can store any data type. Before using the C ++ regular array, you must define it to accommodate all the elements that may be needed. The object created by the MFC array class can be dynamically increased or decreased as needed, the initial subscript of the array is 0, and the upper limit can be fixed. As the element increases, the address of the array in the memory is still continuously allocated.
MFC defines the array template class carray, and defines cbytearray, cwordarray, cuintarray, cdwordarray, cstringarray, cobarray, and cptrarray for various common variable types. See the table below:

Array class Variable type Variable value range Header file
Carray Set various types through parameter types of template classes   Afxtempl. h
Cbytearray 8-bit unsigned integer byte type 0-255 Afxcoll. h
Cwordarray 16-bit unsigned integer word type 0-65535 Afxcoll. h
Cdwordarray 32-bit unsigned integer DWORD type 0-4294967295 Afxcoll. h
Cuintarray 32-bit unsigned integer uint type 0-4294967295 Afxcoll. h
Cstringarray Cstring string   Afxcoll. h
Cobarray Cobject class and its derived class   Afxcoll. h
Cptrarray Void * type pointer   Afxcoll. h

The methods for using the MFC array class are basically the same. The following uses carray and cuintarray as examples to demonstrate how to use the array class.

Use carray

Open VC ++ 6.0 and create a project Array Based on the dialog box. Add the statement in the carraydlg class declaration file (arraydlg. h:

 #include <afxtempl.h>

Remember: Use carray to include the header file afxtempl. h.

Open the resource idd_array_dialog in the Main Dialog Box, and add a button named idc_array_cpoint with the title carray_cpoint. Double-click the button and add the following code to the onarraycpoint () function:

void CArrayDlg::OnArrayCpoint() {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();CClientDC dc(this);dc.MoveTo(0,0);CPoint pt;for(int i=0;i<size;i++){pt=m_Array.GetAt(i);dc.LineTo(pt);}}

Brief Code Description:

CArray <CPoint,CPoint&> m_Array;

This statement defines a carray array object. The template class carray has two parameters. The first parameter is the type of the array element. In this example, It is cpoint, that is, m_array is the cpoint array; the second parameter is of the reference type. Generally, there are two options. One option is the same as the first parameter type, which means that when an array object is passed as a parameter, the array object is passed. The second option is the reference of the first parameter type, which means that when an array object is passed as a parameter, the pointer of the array object is passed. Therefore, we recommend that you use reference transfer to save memory and speed up program running, especially for complex array structure types, just as this example uses cpoint &.

m_Array.SetSize(10,10);

The setsize function sets the array size. This function has two parameters. The first parameter sets the array size. The second parameter sets the size of memory allocation when the array increases. The default value is-1, the default value can be used to ensure a more reasonable memory allocation. In this example, the second parameter is 10, which means that adding an array element will allocate 10 elements of memory for the array.
You can use the setsize function to set the array size at any time. If the first parameter value is smaller than the number of existing members of the array, more members than the first parameter value will be intercepted and the corresponding memory will be released.
Before using the carray array, it is best to use setsize to determine its size and apply for a bucket. If this is not done, when adding elements to the array, You need to constantly move and copy elements to cause low operating efficiency and memory fragmentation.

m_Array.Add(pt1);

Add function to add array elements.

int size=m_Array.GetSize();

Getsize returns the number of array elements.

for(int i=0;i<size;i++){pt=m_Array.GetAt(i);dc.LineTo(pt);}

For intuitive display, this section of code draws the array elements into a line to the screen, where getat (INT index) is worth the corresponding element value through the index. Compile and run the program and observe the running result.

Continue to demonstrate how to use carray

Open the resource idd_array_dialog in the Main Dialog Box and add a button named idc_array_cstring with the title carray_cstring. Double-click the button and add the following code to the onarraycstring () function:

void CArrayDlg::OnArrayCstring() {CArray 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();CClientDC dc(this);dc.SetBkMode(TRANSPARENT);TEXTMETRIC textMetric;dc.GetTextMetrics(&textMetric);int fontHeight=textMetric.tmHeight;int displayPos=10;for(int x=0;x<count;++x){dc.TextOut(10,displayPos,m_string[x]);displayPos+=fontHeight;}AfxMessageBox("Continue...");m_string.RemoveAt(2);count=m_string.GetSize();for(x=0;x<count;++x){dc.TextOut(10,displayPos,m_string[x]);displayPos+=fontHeight;}AfxMessageBox("A string has delete,continue...");m_string.RemoveAll();count=m_string.GetSize();if(count==0)AfxMessageBox("All elements are deleted.");}

Brief Code Description:

m_string.SetAtGrow(2,szdog);

Setatgrow has two parameters. The first parameter determines the sequence number of the array element, and the second parameter is the value of the element. This function sets the value of the corresponding array element based on the serial number value. The function is similar to setat. The difference is that when this function is used to set the element value, if the serial number value is greater than the upper bound of the array, the array automatically increases.
Compile and run the program. You may see that the first line is "tiger" and the second line is "bear", which is expected, however, the third line is an empty string and the fourth line is "dog ". How is empty strings caused? By analyzing the following three lines of code:

m_string.SetAtGrow(0,sztiger);m_string.SetAtGrow(2,szdog);m_string.InsertAt(1,szbear);

In the first line, set element 0 to "tiger", which is unambiguous.
In the second row, element 2 is set to "dog", but element 1 is automatically filled as an empty string while element 2 is set.
In the third row, insert "bear" as element 1, and move the original elements 1 and 2 to elements 2 and 3.

How about this.

m_string.InsertAt(1,szbear);

The insertat function inserts the corresponding element in the specified sequence number. during the execution of the function, the element after the insertion point is automatically moved back. DC. textout (10, displaypos, m_string [x]); where m_string [x] is an overload of the array operator [], the array class carray allows the use of the [] operator, A regular array similar to C ++. M_string [x] can also be replaced by m_string.getat (X.

m_string.RemoveAt(2);

Removeat has only one parameter, that is, the element serial number value. This function deletes the corresponding element value based on the element serial number value, and the subsequent elements are automatically moved forward.

m_string.RemoveAll();

Removeall deletes all element values

Demonstrate how to use the cuintarray class

Open the resource idd_array_dialog in the Main Dialog Box and add a button idc_cuintarray titled cuintarray. Double-click the button and add the following code to the oncuintarray () function:

void CArrayDlg::OnCuintarray() {CUIntArray m_array;m_array.SetSize(5,5);m_array.SetAt(0,0);m_array.SetAt(1,1);m_array.SetAt(2,2);m_array.SetAt(3,3);m_array.SetAt(4,4);int count=m_array.GetSize();CClientDC dc(this);dc.SetBkMode(TRANSPARENT);TEXTMETRIC textMetric;dc.GetTextMetrics(&textMetric);int fontHeight=textMetric.tmHeight;int displayPos=10;for(int x=0;x<count;++x){CString str;str.Format("%d",m_array.GetAt(x));dc.TextOut(10,displayPos,str);displayPos+=fontHeight;}}

This part of the code is not described. Please analyze it yourself.

The removeat and insertat functions shift the array elements during operation. The running time is greater than setat, removeall, and add functions.

I hope this article will help you.

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.