CArray is a collection template which can store all data types.
Unlike a normal C++ Array this MFC Collection template can
grow and shrink depending on the needs. This allows memory to
be utilized efficiently in MFC programs. This template is
declared in afxtempl.h. This class can be used wherever
there is a need to store a list of similar typed objects.
This article describes how to add to, access from and remove objects
from the MFC Collection template CArray.
CArray
- Adding an element:
The member function Add can be used to add objects to the
Array. Before using CArray template, CArray has to be declared to
accept the corresponding type of object. This code sample
declares and uses
CString.
#include
<Afxwin.h>
#include <Afxtempl.h>
void
main()
{
CString l_strValue;
CArray<CString,CString> l_CArray;
for(int i=0;i< 20; i++)
{
//Use the CString format function to create different values
l_strValue.Format("Value %d",i);
//Add the formatted CString to CArray
l_CArray.Add(l_strValue);
}
}
CArray
- Accessing the elements:
The
member function GetAt can be used to access the data stored in
CArray. This returns the object on the type stored. Modifying
the value at a given node is carried out by using SetAt
function.
#include
<Afxwin.h>
#include <Afxtempl.h>
void
main()
{
CString l_strValue;
CArray<CString,CString> l_CArray;
for(int i=0;i< 20; i++)
{
//Use the CString format function to create different values
l_strValue.Format("Value %d",i);
//Add the formatted CString to CArray
l_CArray.Add(l_strValue);
}
//This
part takes care of accessing and printing the data from
CArray
CString l_strGetVal;
for(i=0;i<=l_CArray.GetUpperBound();i++)
{
l_strGetVal = l_CArray.GetAt(i);
printf("%s\n",l_strGetVal);
}
}
CArray
- Removing the elements:
There are two
different functions to remove the data from CArray. RemoveAll
function can be used to remove all the elements. The RemoveAt
function can be used to remove an element from a specific
location.
l_CArray.RemoveAll() //This will remove all the elements from
CArray
l_CArray.RemoveAt(10); //This will remove the 10th element
from CArray
CString was used in the above example with CArray. But all complex data types can be stored in
this MFC Collection template.