class TStudent...{public: TStudent(const TDesC& aName, TUint aId, TInt aScore); void Display() const; // For Sort static TInt CompareById(const TStudent& s1, const TStudent& s2); static TInt CompareByName(const TStudent& s1, const TStudent& s2); // For Find static TBool HasSameName(const TStudent& s1, const TStudent& s2);private: TUint iId; TBuf<10> iName; TInt iScore;};TStudent::TStudent(const TDesC& aName, TUint aId, TInt aScore)...{ iId = aId; iName.Copy(aName); iName.ZeroTerminate(); // Appends a zero terminator onto the end of this descriptor's data. iScore = aScore;}void TStudent::Display() const...{ _LIT(KFormat, "%s %d %d "); console->Printf(KFormat, iName.Ptr(), iId, iScore);}TInt TStudent::CompareById(const TStudent& s1, const TStudent& s2)...{ if (s1.iId == s2.iId) return 0; else return s1.iId > s2.iId ? 1 : -1;}TInt TStudent::CompareByName(const TStudent& s1, const TStudent& s2)...{ return s1.iName.Compare(s2.iName);}TBool TStudent::HasSameName(const TStudent& s1, const TStudent& s2)...{ if (s1.iName.Compare(s2.iName)) return EFalse; else return ETrue;}void Test()...{ _LIT(KTom, "Tom"); _LIT(KJack, "Jack"); _LIT(KMary, "Mary"); _LIT(KJohn, "John"); TStudent tom(KTom, 2, 89); TStudent jack(KJack, 1, 98); TStudent mary(KMary,4, 76); TStudent john(KJohn, 3, 88); RArray<TStudent> arr; CleanupClosePushL(arr); // 记住RArray<T>的入栈方式哦! arr.Append(tom); arr.Append(jack); arr.Append(mary); arr.Append(john); // Before Sort for (TInt i = 0; i < arr.Count(); ++i) arr[i].Display(); console->Printf(_L(" Sort By Name... ")); /* 排序步骤: 1.定义比较函数,如果两个对象相等,返回0;如果第一个大,返回1,否则返回-1. 2.构造TLinearOrder对象,用比较函数的指针初始化 3.对数组调用Sort() */ // Sorted by name TLinearOrder<TStudent> orderByName(TStudent::CompareByName); // 只传递函数名(函数指针),没有括弧哦! arr.Sort(orderByName); for (TInt i = 0; i < arr.Count(); ++i) arr[i].Display(); console->Printf(_L(" Sort By Id... ")); // Sorted by id TLinearOrder<TStudent> orderById(TStudent::CompareById); arr.Sort(orderById); for (TInt i = 0; i < arr.Count(); ++i) arr[i].Display(); /* 查找步骤: 1.定义比较函数 2.构造TIdentityRelation对象,并用比较函数指针初始化 3.构造目标对象 4.调用Find(),传递TIdentityRelation对象参数 */ // Find TStudent goal(KMary, 8, 99); TIdentityRelation<TStudent> identity(TStudent::HasSameName); TInt pos = arr.Find(goal, identity); if (KErrNotFound == pos) console->Printf(_L("Not Founded!")); else console->Printf(_L("Founded at position: %d"), pos); arr.Reset(); // 资源类用完后要Reset CleanupStack::PopAndDestroy(); // 这里是弹栈,因为前面的入栈方式,这里会调用arr.Close();}