
Objects stored in RArray or RPointer array can be sorted basing on any properties you like. Everything you have to do is to define a comparison function to be passed to the Sort() routine.
Here is an example on how to sort the custom CPerson objects by the last name. Note the use of CompareC for taking into account the locale specifics, when comparing strings.
class CPerson : public CBase
{
public:
static CPerson* NewLC( TInt aId, const TDesC& aFirstName,
const TDesC& aLastName );
static TInt CompareByLastName( const CPerson& person1,
const CPerson& person2 );
...
}
TInt CPerson::CompareByLastName( const CPerson& person1,
const CPerson& person2 )
{
return person1.LastName().CompareC( person2.LastName() );
}
...
RPointerArray people;
CleanupClosePushL( people );
CPerson* blake = CPerson::NewLC( 3, _L("John"), _L( "Blake") );
CPerson* bond = CPerson::NewLC( 7, _L( "James" ), _L( "Bond" ) );
CPerson* smith = CPerson::NewLC( 3, _L( "John" ), _L( "Smith" ) );
people.AppendL( smith );
people.AppendL( blake );
people.AppendL( bond );
console->Write( _L( "Before sorting\n" ) );
TLinearOrder byLastName( CPerson::CompareByLastName );
people.Sort( byLastName );
...
As usual see full compilable example attached
| Attachment | Size |
|---|---|
| ArraySort.zip | 3.81 KB |