qsort_b和qsort_r的使用

Apple's Extensions To C中:

The power of a closure is its ability to reference local variables and act upon them while executing in a different activation frame. C API often handles this by allowing a context pointer to be passed in and passed along to a corresponding function and having the custom function treat the opaque context value as a custom structure with appropriate parameterization (see qsort_r). This is cumbersome.

Blocks Programming Topics中:

In many cases, you don’t need to declare block variables; instead you simply write a block literal inline where it’s required as an argument. The following example uses the qsort_b function. qsort_b is similar to the standard qsort_r function, but takes a block as its final argument.

都有對qsort_bqsort_r的舉例說明,這篇文章是介紹這兩個函數(shù)的使用方法:

輸出char數(shù)組:

- (void)_print_char_array:(char **)charArray len:(int)len
{
    for (int i = 0; i < len; i++) {
        char *tmp = charArray[i];
        NSLog(@"%s", tmp);
    }
}

qsort_b的使用

- (void)test_qsort_b
{
    char *myCharacters[3] = { "TomJohn", "George", "Charles Condomine" };
    NSLog(@"qsort_b before");
    [self _print_char_array:myCharacters len:3];
    qsort_b(myCharacters, 3, sizeof(char *), ^(const void *l, const void *r) {
        char *left = *(char **)l;
        char *right = *(char **)r;
        return strncmp(left, right, 1);
    });
    NSLog(@"qsort_b after");
    [self _print_char_array:myCharacters len:3];
}

qsort_b最后一個參數(shù)就是Objective-C的block

qsort_r的使用


typedef struct RXBlockQSortRParam {
    int a;
    int b;
}RXBlockQSortRParam;

static int _s_compar (void *tmp, const void *l, const void *r) {
    RXBlockQSortRParam *param = (RXBlockQSortRParam *)tmp;
    param->a = 10;
    param->b = 100;
    char *left = *(char **)l;
    char *right = *(char **)r;
    return strncmp(left, right, 1);
}
@implementation RXBlockQSortBRObject
- (void)test_qsort_r
{
    char *myCharacters[3] = { "TomJohn", "George", "Charles Condomine" };
    RXBlockQSortRParam param = {0, 0};
    [self _print_char_array:myCharacters len:3];
    NSLog(@"qsort_r before a:%zd, b:%zd", param.a, param.b);
    
    qsort_r(myCharacters, 3, sizeof(char *), &param, _s_compar);
    
    [self _print_char_array:myCharacters len:3];
    NSLog(@"qsort_r after a:%zd, b:%zd", param.a, param.b);
}
@end
// output
qsort_r before a:0, b:0
qsort_r after a:10, b:100

qsort_b的第四個參數(shù)是額外參數(shù),是一個void *的指針,在iOS的Framework中有很多這種方式進行參數(shù)傳遞的。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容