The Add member function can be thought of as providing serial access or serial addition of collection elements. AtPut can be thought of as random access insertion of collection elements more typically associated with arrays.
To add a TCollectibleLong to a collection, use the C++ new operator to create an instance of TCollectibleLong on the heap, then place the pointer returned by new directly into the collection. Creation and addition of an element can be accomplished with a single statement.
Add and AtPut
All collections define an Add member function, but AtPut is defined only for indexed sequences. Thus Add is more general. AtPut, provides a more familiar means of placing elements in an array. AtPut is the functional equivalent of the [] index operator provided by C and Pascal, while Add provides an automated means of adding each of a series of elements to the end of an array, causing the array to grow as necessary when it becomes full.
The Add member function for TArrayOf places the element specified by its argument at the end of the array. Thus if there were no elements already in the array before the above statement is executed, an instance of TCollectibleLong(3) would be at index 0 in the array after the statement is executed. An alternate method for achieving the same effect uses the AtPut member function which takes an integer index and a pointer to an element as arguments. collection->Add(new TCollectibleLong(3));
collection->AtPut(0, new TCollectibleLong(3));
The following code creates a collection designed to hold TCollectibleLongs and then places four TCollectibleLongs into the collection.
TArrayOf<TCollectibleLong>* collection = new TArrayOf<TCollectibleLong>(NIL, NIL); collection->Add(new TCollectibleLong(0)); collection->Add(new TCollectibleLong(1)); collection->Add(new TCollectibleLong(2)); collection->Add(new TCollectibleLong(3));
Indexing arrays
with operator[]
AtPut may seem like an awkward protocol at first even though it is identical to C's [] operator in the function it performs. In fact TArrayOf defines operator[] to allow you to insert and access array elements with a familiar syntax.
To avoid dereferencing the variable collection in the following example, it is declared as an instance of TArrayOf<TCollectibleLong> rather than a pointer.
TArrayOf<TCollectibleLong> collection(NIL, NIL);
TArrayOf<TCollectibleLong> collection(NIL, NIL); collection.GrowTo(4); collection[0] = new TCollectibleLong(0); collection[1] = new TCollectibleLong(1); collection[2] = new TCollectibleLong(2); collection[3] = new TCollectibleLong(3);
NOTE The auto-grow feature of arrays is an option. SetAutoGrow(true) can be used to turn it on. SetAutoGrow(false) turns it off.