The elements of an array can be referenced using the indexing
operator[]
and specifying the position of the element.
For all arrays except the
RArray<class T>
and
RPointerArray<class T>
types, the At()
member function can also be used.
All of the following code fragments use a
CArrayFixFlat<class T>
array.
This code constructs a fixed flat array containing the required
number of TInt
type elements - in this case four.
The indexing operator is used to fetch the value of the second
element and this element is then changed using both the At()
function and the []
operator.
CArrayFixFlat<TInt>* array;
array = new CArrayFixFlat<TInt>(4);
...
for (TInt value = 0; value < 4; value++)
array->AppendL(value);
...
TInt somevalue = (*array)[1]; //fetch the element
TInt somevalue = array->At(1); //... alternative way
(*array)[1] = 21; //change the element
array->At(1) = 21; // ... alternative way
If the array elements are objects of a class with member functions, these functions can be easily accessed as shown in the following code fragment:
class TMyClass
{
public :
void SetValue(TInt aval);
TInt GetValue();
private
TUint iValue;
};
CArrayFixFlat<TMyClass>* array; // an array of
// TMyClass objects
TMyClass myclass;
array = new CArrayFixFlat<TMyClass>(1);
array->AppendL(myclass);
(*array)[0].SetValue(21);
Where the elements are pointers to CBase
derived objects
(i.e. elements of an array of type CArrayPtrFlat
or
CArrayPtrSeg
), the members of those CBase
derived
objects can easily be accessed. For example, an array of pointers to
CElement
objects can be accessed as follows:
CArrayPtrFlat<CElement>* ptrflat;
...
ptrflat = new (ELeave) CArrayPtrFlat<CElement>(16)
...
... // add elements to ptrflat
...
(*ptrflat)[0]->SetTextL(_LIT("New text for the first CElement"));
ptrflat->At(1)->SetTextL(_LIT("New text for the second CElement"));
(where SetTextL()
is a member function of
Celement)
.
Note that both At()
and the index operator[]
return a reference to the object in the array.
If a pointer to the referenced object is taken, be aware that the pointer value may become invalid once elements are added to, or removed from the array. In this event, always refresh the pointer.
class TMyClass
{
public :
void SetValue(TInt aval);
TInt GetValue();
private
TUint iValue;
};
CArrayFixFlat<TMyClass>* array;
...
TMyClass myclass;
array = new CArrayFixFlat<TMyClass>(16);
...
for (TInt val = 0; val < 10; val++)
{
myclass.SetValue(val)
array->AppendL(myclass;
}
...
TMyClass* myptr;
myptr = &(array->At(9));
myptr->GetValue(); // references the tenth element
array->Delete(0,4); // Delete first four elements
array->Compress();
myptr->GetValue(); // myptr is invalid. An exception may occur
...
After deleting the first four elements, myptr
points to a
location outside the logical array. Once the array has been compressed, the
pointer is invalid.