std::lower_bound and std::find on a plain array

Abruzzo Forte e Gentile picture Abruzzo Forte e Gentile · Jun 1, 2012 · Viewed 25.2k times · Source

I like to use std::algorithm whenever I can on plain arrays. Now I have 2 doubts; suppose I want to use std::lower_bound what happens if the value I provide as argument is not found?

int a[] = {1,2,3,4,5,6};
int* f = std::lower_bound(a,a+6,20);

The result I have when printing *f is 20.

The same happens if I use std::find.

int a[] = {1,2,3,4,5,6};
int* f = std::find(a,a+6,20);

The result I have when printing *f is 20.

  1. Is it always the case that the return value is the original argument when this is not found?
  2. In terms of performance std::lower_bound performs better of std::find since it implements a binary search algorithm. If the array is big say max 10 elements, could std::find perform better? Behind the scenes std::lower_bound calls std::advance and std::distance ..maybe I might save on these calls as well?

Thanks a lot

AFG

Answer

Robᵩ picture Robᵩ · Jun 1, 2012

The result I have is 20. (Later edited to: The result I have when printing *f is 20.)

No, the result you get is a+6. Dereferencing that invokes undefined behavior. It might print 20, it might print "Shirley MacLaine", or it might blow up your car.

Is it always the case that the return value is the original argument when this is not found?

The return value will always be the 2nd argument in your case, because 20 is larger than any other value in the array. If the value is not found, but smaller than some existing value, the return value points to the next larger item.

From cppreference.com, the return value of std::lower_bound is "iterator pointing to the first element that is not less than value, or last if no such element is found."

In terms of performance ...

Measure it. No other advice here will stand up to your actual empirical evidence.

Behind the scenes std::lower_bound calls std::advance and std::distance ..maybe I might save on these calls as well?

Almost certainly not. Those calls are almost certainly optimized in your case to single (or very few) instructions.