Does an implementation of std::lower_bound() exist, which is optimized for sorted and unique integer sequences?
Does an implementation of std::lower_bound() exist, which is optimized for sorted and unique integer sequences?
lower_bound is pretty close to optimal for integer sequences, and ONLY works on sorted sequences. unique doesn't change much really.
The only thing worth optimizing is if your integers have a specific distribution, in which case there are slightly more optimal algorithms, but none are implemented in the standard library. I assume this is because the implementations require items where comparisons are integer based, and also have specific distributions, which makes them pretty specific to the data, and thus not a good fit for a standard library.
However, if you have a BILLION items to search through, lower_bound still only takes 30 comparisons, so... its not worth further optimization. I can pretty much guarantee that optimizing this search will not make real programs noticeably faster.
Yes. It's called binary_search. It will return true if the element exists in the sequence, and false otherwise.
#include <vector>
#include <algorithm>
#include <cassert>
int main () {
std::vector<int> v = { 0, 2, 4, 6, 8 };
assert (!std::binary_search(v.begin(), v.end(), 1));
assert ( std::binary_search(v.begin(), v.end(), 4));
}
[Later] Ok, I completely misread the question :-(
lower_bound works fine on a sorted sequence.
It turns out that the sequence needs only to be partitioned, but a sorted sequence satisfies that criterion.
See CppReference.