I need a binary search algorithm that is compatible with the C++ STL containers, something like std::binary_search
in the standard library's <algorithm>
header, but I need it to return the iterator that points at the result, not a simple boolean telling me if the element exists.
(On a side note, what the hell was the standard committee thinking when they defined the API for binary_search?!)
My main concern here is that I need the speed of a binary search, so although I can find the data with other algorithms, as mentioned below, I want to take advantage of the fact that my data is sorted to get the benefits of a binary search, not a linear search.
so far lower_bound
and upper_bound
fail if the datum is missing:
//lousy pseudo code
vector(1,2,3,4,6,7,8,9,0) //notice no 5
iter = lower_bound_or_upper_bound(start,end,5)
iter != 5 && iter !=end //not returning end as usual, instead it'll return 4 or 6
Note: I'm also fine using an algorithm that doesn't belong to the std namespace as long as its compatible with containers. Like, say, boost::binary_search
.
std::lower_bound
, but I believe that is the way to go for binary search, see here. You just need to check for end and then for equality with your needle, instead of just checking for the end. It is only a small constant cost andlower_bound
should be as fast asbinary_search
, unless your data contains a lot of repetition, in which casebinary_search
may find the needle slightly faster if it is present (if it is not, then it needs to find lower/upper bound anyway). – Hysterectomize