Introduction.
This turorial
will demonstrate the the MFC
collection classes CList,
CArray
and
CMap
. These
classes are an excillent way to manage dynamic data in a
type safe manner. They are very easy to use and mostly
encourage solid code.
Quick
Start.
Collection Data Types.
Using CArray.
Using CList.
Using CMap.
Using pointers to objects.
A Quick
Start.
Lets just use
a simple List collection to start with. This example
demonstartes a que of shoe sizes held as doubles. Items
are added to the Tail of the que and removed from the Head
for processing.
#include <afxtempl.h> // MFC suport for Collections
...
//Declare the que object
CList<double, double> m_lstShoeSize;
//Add items to the que
m_lstShoeSize.AddTail( 10.5 );
m_lstShoeSize.AddTail( 8.0 );
m_lstShoeSize.AddTail( 9.5 );
m_lstShoeSize.AddTail( 9.0 );
//Process (show) the items in the list.
for( POSITION pos = m_lstShoeSize.GetHeadPosition(); pos != NULL; )
{
_tprintf( _T("Shoe size is %4.1lf\n"), m_lstShoeSize.GetNext( pos ) );
}
//Process (remove) the items from the que
while( !m_lstShoeSize.IsEmpty() )
{
double dRemovedShoe = m_lstShoeSize.RemoveHead();
_tprintf( _T("Removing Shoe Size(%4.1lf)\n"), dRemovedShoe );
}
Collection
data types.
Jump ahead to
using CArray
if you just want to skip the theory. In the previous example
you would note the use of a template
. The two parameters
are used to define how data is stored and retrieved
from the collection.
TYPE.
This is the
type of data that is used to hold the elements internally
and RETURNED from the collection. Get returns this data
type.
ARG_TYPE.
This type is
use to specify the type of data used to write (STORE) data
to the collection. Set uses this data type. Often this
type is a reference to the TYPE value. Some examples
follow;
CList< PERSON*, PERSON* > m_lstPeople; //1 List of pointers to struct
CList< CString, CString > m_lstNames; //2 List of CStrings
CList< CString, CString&> m_lstNames; //3 .. same using references
CList< CString, LPCSTR > m_lstNames; //4 .. using constant pointers
Note 1: With
regard sample 1, the list contains pointer not objects, so
the objects must be created with new and deleted when no
longer required.
Note 2: With
regard sample 3, the ARG_TYPE parameter is used to
indicate how the value will be passed into the collection,
ie in the Add() method. It does NOT indicate a collection
of referances.
Using CArray.
CArray
is a collection that is best used for data that is to be
accessed in a random or non sequensial manner. The array
can dynamically shrink and grow as necessary. Array
indexes always start at position 0. You can decide whether
to fix the upper bound or allow the array to expand when
you add elements past the current bound. Memory is
allocated contiguously to the upper bound, even if some
elements are null.
The following
example adds two CTime
objects to the array and then displays the contents of the
entire array. The key functions are SetAtGrow
which
adds an item and increases the array size and the []
operator which is used to retrieve data from the
array.
#include <afxtempl.h> // MFC suport for Collections
...
CArray<CTime, CTime&> m_aryTime;
m_aryTime.SetAtGrow( 3, CTime::GetCurrentTime() );
m_aryTime.SetAtGrow( 5, CTime( 1999, 6, 12 ) );
for( int nCnt = 0; nCnt < m_aryTime.GetSize(); nCnt++ )
{
if( m_aryTime[nCnt].GetTime() != 0 )
{
_tprintf( _T("Time is %s\n"),
m_aryTime[nCnt].Format( _T("%d/%b/%y %H:%M") ) );
}
else
{
_tprintf( _T("Invalid Time\n") );
}
}
Using CList.
Lists are
simular to arrays but are optimised for data that is read
in a more sequensial manner such as ques and lists. See
the example in Quick Start.
earlier for a simple list example. Note items are added at
the head or tail of the list. Retrival is from the head or
tail of the list and via an iterative process.
#include <afxtempl.h> // MFC suport for Collections
...
//Declare the que object
CList<int, int> m_lstDepth;
//Add items to the que
m_lstDepth.AddTail( 100 );
m_lstDepth.AddTail( 85 );
m_lstDepth.AddTail( 95 );
m_lstDepth.AddTail( 90 );
//Process (show) the items in the list.
for( POSITION pos = m_lstDepth.GetHeadPosition(); pos != NULL; )
{
_tprintf( _T("Dive depth is %4d\n"), m_lstDepth.GetNext( pos ) );
}
Using CMap.
The CMap
object is an simple collection, but unlike arrays and
lists, which index and order the data they store, maps
associate keys and values. To access a value stored in a
map, specifying the value˘Î associated key. This is
simular to a hash table.
#include <afxtempl.h> // MFC suport for Collections
...
CMap<CString,LPCSTR,CString,CString&> m_mapAddress;
m_mapAddress[_T( "10.1.1.102" )] = _T("BILL");
m_mapAddress[_T( "10.1.1.108" )] = _T("MAILSERVER");
m_mapAddress[_T( "10.1.1.112" )] = _T("DevLaptop01");
m_mapAddress[_T( "10.1.1.10" )] = _T("PALEALE");
m_mapAddress[_T( "10.1.3.1" )] = _T("PTRAK");
CString sMachine;
CString sUnknownIP = _T( "?0.?.?.112" );
sUnknownIP.Replace( _T("?"), _T("1") );
m_mapAddress.Lookup( sUnknownIP, sMachine );
_tprintf( _T("Machine at IP %s is %s\n"), sUnknownIP, sMachine );
Using
pointers to objects.
In all the
previous examples the items in the list all supported the
assigment =
operator. This makes it possible
to add and retrieve data from the collection. Items that
do not support the assignment operator can still be saved
to a collection but must be created and destroyed manualy.
The objects must be dynamically allocated using the new
operator, ie the "free store" or
"heap" this ensures they are not deleted once
they go out of scope. Therefore when removed from the list
they must be manually deleted. A destructor is often good
place to perform this tucancode.net. The following example shows a
list of PERSON structures that are created, displayed and
deleted.
NOTE: Unlike
other collections, pointers return the actual object
rather than a copy, so changes made to the returned object
are perminent.
#include <afxtempl.h> // MFC suport for Collections
...
//Person structure
#define LEN_CLOTH_SIZE (5) //Max cloth size length
typedef struct _PERSON
{
int nHeight; //in cm
CString sFullName; //Name
COleDateTime tmBirthDate; //Birthday
TCHAR szShirt[LEN_CLOTH_SIZE]; //Shirt size
} PERSON, *LPPERSON;
...
CList< LPPERSON, LPPERSON > m_lstPeople;
//Bilbos details
LPPERSON lpPerson = new PERSON;
lpPerson->nHeight = 95;
lpPerson->sFullName = _T("Bilbo Baggins");
_tcscpy( lpPerson->szShirt, _T("XOS") );
lpPerson->tmBirthDate = COleDateTime( 1965, 6, 22, 3, 0, 0 );
m_lstPeople.AddTail( lpPerson );
//Fredo details
lpPerson = new PERSON;
lpPerson->nHeight = 49;
lpPerson->sFullName = _T("Fredo Frog");
_tcscpy( lpPerson->szShirt, _T("OS") );
lpPerson->tmBirthDate = COleDateTime( 1965, 1, 5, 18, 0, 0 );
m_lstPeople.AddTail( lpPerson );
//Display the People in the que
POSITION posPerson = m_lstPeople.GetHeadPosition();
while( posPerson != NULL )
{
LPPERSON lpDisplayPerson = m_lstPeople.GetNext( posPerson );
_tprintf( _T("Name .........%s\n"), lpDisplayPerson->sFullName );
_tprintf( _T("Height %d\n"), lpDisplayPerson->nHeight );
_tprintf( _T("Shirt size %s\n"), lpDisplayPerson->szShirt );
_tprintf( _T("Birthday %s\n\n"), lpDisplayPerson->tmBirthDate.
Format( _T("%d/%b/%y %H:%M") ) );
}
//Free out the list
while( !m_lstPeople.IsEmpty() )
{
LPPERSON lpLostPerson = m_lstPeople.RemoveHead();
delete lpLostPerson;
}
Note:
UCanCode Advance E-XD++
CAD Drawing and Printing Solution
Source Code Solution for C/C++, .NET V2024 is released!
Contact UCanCode Software
To buy the source code or learn more about with: