Things You'll Need:
- Book on MFC such as "Programming Windows with MFC" by Jeff Prosise
- Microsoft Visual Studio IDE
-
Step 1
Understand the class declaration or prototype as shown below. The first parameter, TYPE, specifies what type of objects are stored in and returned by the array. The second parameter, ARG_TYPE, indicates the type of argument used for accessing an object. Often, ARG_TYPE is a reference to the first parameter. Those with knowledge of the Standard Template Library of pure C++ will notice the MFC CArray prototype's resemblance to that of the Map container:
template < class TYPE, class ARG_TYPE > class CArray : public CObject -
Step 2
Know the basics of the MFC CArray. The indexing is zero-based. That is, the first element is at position 0, while the last element is at position "array_size-1." If the CArray object is of size 10, then its last element is at position 9. The array size can be preset, or the elements can be added one by one, allowing the array to grow past its current size. The memory allocations are contiguous by default, until the memory sector is exceeded.
-
Step 3
Pre-allocate memory for the array. Do this right after the declaration. Even if you don't know the size the array will reach, make a liberal estimate. Pre-allocation reserves a contiguous (continuous) memory area where the array will reside. When the memory has no discontinuities, array operations are more efficient and copying and data transfers are prevented. For this operation, use the "SetSize()" function.
-
Step 4
Add objects to the array by using the "Add()" function as shown below:
CArray < CPoint,CPoint > pArr;
pArr.Add(CPoint(20, 40)); -
Step 5
Access elements stored in the array. You can do this through the "GetAt()" function and through the "[]" operator as in all other arrays. "GetAt()" accepts an index integer and returns the element stored at that location. Its opposite is "SetAt()" that changes a value for a given index.
-
Step 6
Remove an element from the array. For this, you can use the "RemoveAt()" or the "RemoveAll()" function. "RemoveAll()" clears the CArray object of all the elements. "RemoveAt()" accepts two inputs, an integer index and the number of elements to be removed starting from that location:
void RemoveAt( int nIndex, int nCount = 1 );










