C++ std::lower_bound
std::lower_bound returns the first iterator whose element is at least the lookup value under the default ordering.
A simple example
std::lower_bound
- Start with Sorted values 1, 3, 5
- Do this Find the first value at least 2
- Result 3
Syntax
std::lower_bound(first, last, target)
Run this example in C++
Save the program as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson
Find the first eligible price tier
A price catalog is already sorted and can contain repeated thresholds. Locate the correct boundary and check what the returned position means when an exact value is absent.
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> tiers{10, 20, 20, 40};
for (int target : {20, 41}) {
auto it = std::lower_bound(tiers.begin(), tiers.end(), target);
if (it == tiers.end()) std::cout << "no tier\n";
else std::cout << (it - tiers.begin()) << '\n';
}
return 0;
}
1 no tier
Sort the range before searching. A target above every price returns the end iterator, which must be checked before dereferencing. Equal tiers resolve to the first match.
C++ working draft for std::lower_bound
Locate a numbered tote
A parcel clerk keeps tote numbers in ascending order. Find the specified item in the sorted register. How many smaller entries come before it?
Find the earliest permit
A permit clerk starts with the smallest valid identifier. Find the specified item in the sorted register. How many smaller entries come before it?