RPointerArray

来源:互联网 发布:域名注册哪个便宜 编辑:程序博客网 时间:2024/06/15 21:12
 
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, 
289);
    TStudent jack(KJack, 
198);
    TStudent mary(KMary,
476);
    TStudent john(KJohn, 
388);

    RPointerArray
<TStudent> arr; // 仍用类名实例化模板,不过存放的是T*
    CleanupClosePushL(arr); // 记住RPointerArray<T>的入栈方式哦!

    arr.Append(
&tom); // 这里添加的是地址
    arr.Append(&jack);
    arr.Append(
&mary);
    arr.Append(
&john);

    
/*
    排序步骤:
    1.定义比较函数,如果两个对象相等,返回0;如果第一个大,返回1,否则返回-1.
    2.构造TLinearOrder对象,用比较函数的指针初始化
    3.对数组调用Sort()
    
*/

    
// Before Sort
    for (TInt i = 0; i < arr.Count(); ++i)
        arr[i]
->Display();

    console
->Printf(_L(" Sort By Name... "));
    
    
// 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, 899);
    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(); // 这里是弹栈