コードケース(構造体、関数ポインタ、ポインタ関数、バブルソート)修正分類:C言語2014-09-19 16:01 16人読書コメント(0)コレクション

2376 ワード

#import <Foundation/Foundation.h>
typedef struct
{
    char name[20];
    int age;
    float score;
}Stu;
//                 .
typedef BOOL (*PStu) (Stu stu1,Stu stu2) ;
typedef struct nameFunctionPair{
    char name[20]; //          
    PStu function;   //            
}NameFunctionPair;
//     
BOOL sortStudentByAge(Stu stu1,Stu stu2 )
{
    return stu1.age > stu2.age;
}
//  
BOOL sortStudentByScore(Stu stu1,Stu stu2 )
{
    return stu1.score > stu2.score;
}
//  
BOOL sortStudentByName(Stu stu1,Stu stu2  )
{
    return strcmp(stu1.name, stu2.name) >0;
}
PStu getFunctionByName (char *name , NameFunctionPair *p , int count )
{ int i = 0;
    for (i = 0 ; i < count; i ++) {
        if (strcmp(name, (p + i)->name) == 0) { //          ,       
            return (p + i)->function;
        }
    }
    return NULL;  //            ,   NULL;
}

//              ,           .
void sortStudent(Stu *p , int count , char *name, NameFunctionPair *pair, int number)
{
    PStu funtion =   getFunctionByName(name, pair, number);

    for (int i = 0 ; i < count -1; i ++) {
        for (int j= 0 ; j < count -1-i; j ++) {
            if (funtion(*(p + j),*(p + j + 1))) {
                Stu temp  = *(p + j);
                *(p + j) = *(p + j + 1);
                *(p + j + 1) = temp;
            }
        }
    }
}
void outPut(Stu *p , int count )
{
    for (int i = 0 ; i < count ; i ++) {
        printf("name = %s , age = %d , score = %.2f
" , (p + i)->name,(p + i)->age , (p + i)->score);     } } // , . //name  //p  //count   int main(int argc, const char * argv[]) {     Stu stu[5] = {         {"zhang",20,80},         {"wang", 22,82},         {"li",23,86},         {"zhao",22,83},         {"liu",20,89}     };     Stu *p = NULL;     p = stu;     //     NameFunctionPair name[3] = {         {"name",sortStudentByName},         {"score" , sortStudentByScore},         {"age" , sortStudentByAge}     };     char tempName[20] = {0};     printf(" ( :name ,  : age ,  : score)
");     scanf("%s",tempName);       //     sortStudent(p, 5, tempName, name, 3);     outPut(p, 5);             return 0; }

本文はブロガーのオリジナル文章で、ブロガーの許可を得ずに転載してはならない.