Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::lower_bound and comparator function with different types?

Tags:

c++

stl

I have an array of structures, sorted on a member of a structure, something like:

struct foo
{
    int bar;
    double baz;
};

// An array of foo, sorted on .bar
foo foos[] = { ........ };
// foos[0] = {0, 0.245}
// foos[1] = {1, -943.2}
// foos[2] = {2, 304.222}
// etc...

I want to find the element with a specific .bar value. It might or might not be in the array, and I'd like to do it in O(log(n)) time, since the array is sorted.

std::lower_bound is what I'd normally go for, but I need to specify a comparison function. However, the type of the members of the array (struct foo) and the searched value (int) are not the same, thus, my comparator is:

bool comp(foo a, int b)
{
    // ...
}
// --- or ---
bool comp(int a, foo b)
{
    // ...
}

It looks like the first will work with gcc, but I was wondering if the order of the arguments to the comparison function was specified by the standard, or if I'm relying on compiler behavior.

I'd like to avoid constructing a foo to pass to std::lower_bound here, as a full foo isn't required, and could be costly. My other option would be to wrap the foo * in a custom iterator that only exposed the .bar member.

like image 374
Thanatos Avatar asked Feb 21 '11 22:02

Thanatos


1 Answers

From the standard, 25.3.3.1/3, on std::lower_bound():

Returns: The furthermost iterator i in the range [first, last] such that for any iterator j in the range [first, i) the following corresponding conditions hold: *j < value or comp(*j, value) != false.

From that, you may use

bool comp(foo a, int b)

or you may compare two foo instances and then access bar in both of them.

like image 140
wilhelmtell Avatar answered Oct 28 '22 10:10

wilhelmtell