Searching and Sorting

来源:互联网 发布:上海日料放题 知乎 编辑:程序博客网 时间:2024/05/17 00:53

bsearch 和 _lfind参数3不同, 传值uCnt.
没有去单步bsearch, 从使用者角度看, 和_lfind一样.

实验

// test1958.cpp : Defines the entry point for the console application.// Searching and Sorting - bsearch#include "stdafx.h"#include <windows.h>#include <search.h>#include <string.h>#include <stdio.h>#include <stdlib.h>int compare1(const void* pAry, const void* ppArgToSearch){    return(_stricmp(*(char**)ppArgToSearch, (char*)pAry));}void testcase1() {    char* result = NULL;    char* key = "123";    UINT uCnt = 5;    char* szMsgAry[6] = {        "msg1",            "msg2",            "msg3",            "msg4",            "msg5",            NULL,    };    // if not found uCnt++, but can't add to ary, the elment was added is wrong...    // if "123" not found, change szMsgary[5] 0x00333231, this is a bug...    // 这函数没啥大用..., 只有list元素内容是内建数据类型(且不是指针)时,才好使.    result = (char*)_lsearch(key, szMsgAry, &uCnt, sizeof(szMsgAry[0]), compare1);    if (result) {        printf("%s found\n", result);    } else {        printf("hello not found!\n");    }}int compare2(const void* pSearch, const void* ppArg){    int iSearch = *(int*)pSearch;    int iAry = *(int*)ppArg;    if (iSearch > iAry) {        return 1;    } else if (iSearch == iAry) {        return 0;    } else {        return -1;    }}void testcase2() {    int* pFind = NULL;    int key = 1940/*2017*/;    UINT uCnt = 5;    int iAry[6] = {        1900,            1910,            1920,            1930,            1940,            1950,    };    // bsearch 和 _lfind参数3不同, 传值uCnt    // 没有去单步bsearch, 从使用者角度看, 和_lfind一样    pFind = (int*)bsearch(&key, iAry, uCnt, sizeof(iAry[0]), compare2);    if (NULL != pFind) {        printf("%d found\n", *pFind);    } else {        printf("%d not found!\n", key); // 没找到会到这里    }}void main(unsigned int argc, char** argv){    // testcase1();    testcase2();    system("pause");}
0 0
原创粉丝点击