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.
From the standard, 25.3.3.1/3, on
std::lower_bound():From that, you may use
or you may compare two
fooinstances and then accessbarin both of them.