Home > OS >  use of std::bsearch issues no suitable conversion function error for comparator
use of std::bsearch issues no suitable conversion function error for comparator

Time:01-03

I have this use of std::bsearch that accesses some_file defined in scope of this function:

int foo = bsearch(&key, (int *)arr   1, count, sizeof(int), 
                 [&](int *offset_a, int *offset_b) -> int
                    { string name_a = *(string *)((int *)some_file   *offset_a);
                    });

and I get:

no suitable conversion function from "lambda [](const int *offset_a, const int *offset_b)->int" to "__compar_fn_t" existsC/C (413)

I was wondering how I can fix this without compromising functionality.

CodePudding user response:

As you can see in the std::bsearch documentation:

The signature of the comparison function should be equivalent to the following:

int cmp(const void *a, const void *b);

I.e. comp should be a C style function pointer or something that can be converted to one.

A lambda with capture (like in your case due to the [&]) cannot be converted into a C style function pointer.
This is because lambdas with capture are actually under-the-hood classes with a call operator, and data members for the captures.
Some more info: Lambda expressions.

You'll need to either use a plain function pointer, or a lambda without any capture.


Edit:
Alternatively (as @KonradRudolph commented), you can replace the C function bsearch with a similar C function, e.g. std::lower_bound, where you can pass any lambda for the comparator.

  • Related