Re: How can I use CArray efficiently?

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



On Mon, 9 Apr 2007 10:17:36 -0700, "David Ching"
<dc@xxxxxxxxxxxxxxxxxxxxxx> wrote:

You're right, as the fellow who actually did the test and printed out the
results confirmed. (I was confusing CArray with CHashTable, which also has
an init size method.) Well then, this is quite confusing. If SetSize(100)
is called to allocate the first 100 elements so they will be stored quickly,
then GetSize() returns 100. But then how to iterate the array to visit all
items? The doc gives the example of using GetSize()!

CTypedPtrArray<CObArray, CPerson*> myArray;
for( int i = 0; i < myArray.GetSize();i++ )
{
CPerson* thePerson = myArray.GetAt( i );
...
}

So even if zero items are added, this loop still executes 100 times! I
wonder what GetAt() returns for these non-existant items? I guess I should
find out, but I guess I've not used SetSize() before ...

The obvious thing for CArray to do is default-construct the new items when
SetSize is called. I think that's what the deprecated helper
ConstructElements does nowadays; oh wait, it seems to have disappeared
entirely in VC2005. Better take those deprecated warnings seriously, I
guess.: )

(Note that vector::resize allows you to pass in an object to be copied to
the new items, so your stored type needn't be default-constructible. That's
the sort of thing MFC tends to ignore, because people just weren't thinking
in those terms back in the day.)

--
Doug Harrison
Visual C++ MVP
.