首页 文章

如何使用std :: bsearch的成员函数

提问于
浏览
3

我有一个C类,但我也使用一些低级别的C,需要使用 bsearch 函数 . bsearch 的最后一个参数是一个比较函数,我想以一种允许它访问类的const私有变量的方式实现所述函数 .

问题是,如果我将比较函数作为成员函数,它将无法工作,因为它不能转换为常规函数指针 . 如果我创建一个非成员函数,我可以将其传递给 bsearch ,但无法访问该类的私有变量 .

该怎么办?

示例:
enter image description here

3表示有3个元素.16,32,56是偏移字节 . 我需要bsearch来搜索actors.I我在偏移数组中搜索 . 我需要一个比较函数来比较actor但我也需要const void * actorFile用于计算比较函数中位置的指针.actorFIle是类私有变量 .

2 回答

  • 1

    解决方案是放弃C库函数,并使用C作为's meant to be used. The C++ standard library also has a utility search function, it',称为std::lower_bound . 它接受类似通用函数的对象,而不仅仅是常规函数指针 .

    这允许您使用捕获您的类的lambda表达式来调用它:

    std::lower_bound(start, finish, value, [this] (auto const& lhs, auto const& rhs) {
                     /* Compare and utilize anything this can point to*/ });
    
  • 7

    如果你真的与 bsearch 绑定,只需在非成员函数中使用你的成员函数 . 因此,您无需访问私有成员 .

    /* Create global variable to use in compare proc*/
    actors_data_base* cmp_data_base = NULL;
    
    /* Write compare routine like */
    int cmp_proc(const void * a, const void * b)
    {
        size_t a_offset = static_cast<size_t>(a);
        size_t b_offset = static_cast<size_t>(b);
        return cmp_data_base->compare_actors(a_offset, b_offset);
    }
    
    
    /* Set global pointer and use bsearch */
    actors_data_base = &my_data_base;
    bsearch(&my_value, array, size, sizeof(size_t), cmp_proc);
    

    当然,由于使用了全局变量,这很难看 . 但这是传递上下文来比较proc的唯一方法 . 您可以考虑使用线程本地存储来避免线程问题(由于全局变量,不得同时使用 cmp_proc

    因此,使用std::lower_bound会更好 .

相关问题