×
Namespaces

Variants
Actions

How to sort elements of RArray and RPointerArray

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Article
Created: savaj (10 Mar 2009)
Last edited: hamishwillee (04 Dec 2012)
Objects stored in RArray or RPointer array can be easily sorted inplace based on a custom ordering algorithm. To achieve this developer needs to define a custom ordering function that compares two instances of the stored objects and returns an integer based on the comparison. To sort a RArray/RPointerArray simply pass this function to the RArray/RPointerArray::Sort function by packaging it in a TLinearOrder object. Following example shows how to sort RPointerArray, similarly we can sort RArray.
//declaration of class.
class CPerson: public CBase
{
// other functions are removed for sake of simplicity.
public:
/** Sort Order By Name**/
static const TLinearOrder<CPerson> KSortOrderByName;
 
private:
/**Comparator Function for sort by name**/
static TInt CompareByName( const CPerson& aNameOne,const CPerson& aNameTwo );
 
private:
/**instance data*/
HBufC* iName;
};
/**initialize the sort order to use CPerson::CompareByName*/
const TLinearOrder<CPerson> CPerson::KSortOrderByName(CPerson::CompareByName);
 
/**comparision function, it compare two names.*/
TInt CPerson::CompareByName( const CPerson& aNameOne, const CPerson& aNameTwo )
{
return aNameOne.iName->Des().CompareC( aNameTwo.iName->Des() );
}
 
/************************************************************************/
//the pointer array in to be sorted
RPointerArray<CPerson> elementArray;
 
//assuming we created all objects of class CPerson sucessfully.
elementArray.Append(pPerson1)
elementArray.Append(pPerson2)
elementArray.Append(pPerson3)
elementArray.Append(pPerson4)
 
//sorting elementArray by name.
elementArray.Sort(CPerson::KSortOrderByName);
This page was last modified on 4 December 2012, at 02:48.
48 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×