c语言----bsearch使用

 1 //------------------------------------------
 2 //      c语言 qsort 测试 
 3 //函数原型:
 4 //_ACRTIMP void* __cdecl bsearch(
 5 //    _In_                                               void const* _Key,
 6 //    _In_reads_bytes_(_NumOfElements * _SizeOfElements) void const* _Base,
 7 //    _In_                                               size_t      _NumOfElements,
 8 //    _In_                                               size_t      _SizeOfElements,
 9 //    _In_                _CoreCrtNonSecureSearchSortCompareFunction _CompareFunction
10 //);
11 //
12 //参数介绍:
13 //    参数1: 要查找的关键字的地址,地址的类型和base的类型保持一致
14 //  参数2: 要查找的内容的基地址,其中的内容会被交换,内容可以是数据内容,也可是指针地址。
15 //
16 //            warning:    查找之前,基地址中的内容必须是有序的,要进行排序
17 //
18 //  参数3: 要查找的内容的总数量
19 //  参数4: 查找的内容的数据类型的大小
20 //  参数5: 比较函数,其中的比较可以是你排序内容直接比较的结果,也可以是其指针内的某一小块内容比较的结果,排序和查找保持一致
21 //
22 //返回值类型:
23 //    void* : 返回对应查找内容的地址, 需要强制转成对应的数据类型地址,便于访问对应的地址中的相关信息
24 //        若返回为NULL,表示没有找到数据
25 //
26 //eg: 对 整数 数组 进行查找
27 //   
28 //
29 //-------------------------------------------
30 
31 #include "gtest/gtest.h"
32 #include <iostream>
33 using namespace std;
34 
35 int bsearch_com(const void *a, const void *b)
36 {
37     int* tem1 = (int*)a;
38     int* tem2 = (int*)b;
39     if ((*tem1) > (*tem2))
40         return -1;
41     else if ((*tem1) < (*tem2))
42         return 1;
43     else
44         return 0;
45 }
46 void test_bsearch()
47 {
48     int num = 6;
49     int a[6] = { 1,7,8,4,6,3 };
50     int key = 6;
51 
52     //查找之前数组必须经过排序
53     qsort(a, num, sizeof(int), bsearch_com);
54     //查找
55     int* tem = (int*)bsearch(&key, a, num, sizeof(int), bsearch_com);
56     if (tem == NULL) {
57         cout << "no find" << endl;
58     } else {
59         cout << tem << "   " << *tem << endl;
60     }
61     key = 2;
62     tem = (int*)bsearch(&key, a, num, sizeof(int), bsearch_com);
63     if (tem == NULL) {
64         cout << "no find" << endl;
65     } else {
66         cout << tem << "   " << *tem << endl;
67     }
68 }
69 
70 TEST(test, test_01)
71 {
72     test_bsearch();
73 }

 

posted @ 2020-04-09 19:28  博客园—哆啦A梦  阅读(406)  评论(0)    收藏  举报