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

标签 c++ c class bsearch

我有一个 C++ 类,但我也在使用一些低级 C 并且需要使用 bsearch 函数。 bsearch 的最后一个参数是一个比较函数,我想以一种允许它访问类的常量私有(private)变量的方式实现所述函数。

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

怎么办?

例子: enter image description here

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

最佳答案

解决方案是放弃 C 库函数,并按应有的方式使用 C++。 C++标准库也有实用搜索功能,叫做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*/ });

关于c++ - 如何使用 std::bsearch 的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46661168/

相关文章:

c++ - 将 tprintf 用于 TCHAR argv[0] 并获取问号

c++ - C/C++ : Is it possible to configure the Eclipse project settings to accept void pointer without casting for all Linux distros

python - 有没有免费的 Python 到 C 的翻译器?

android - 从 Android 代码定义 C 宏

c - STM32:将地址映射存储在数组中

c# - 如何在公共(public)类中出于只读目的访问私有(private)抽象的成员?

C++ - 高级多态性 : Is this function legal for removing pointers from a list?

c++ - 通过 ActiveX 在 WPF 中使用 OpenGL?

c++ - 使用宏增加 C++ 代码的详细程度

java - 简单计算器的实现