Syntax
auto it = std::lower_bound(values.begin(), values.end(), target);Examples
C++ std::lower_bound searches
Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> times{10, 20, 20, 40};
auto it = std::lower_bound(times.begin(), times.end(), 20);
if (it != times.end() && *it == 20)
std::cout << "First index: " << (it - times.begin()) << '\n';
}- Output: First index: 1. The iterator points to the first duplicate, not an arbitrary matching element.
Best practices
- Maintain the ordering and check end before dereferencing. Finding an insertion point does not itself prove equality.
Runtime & versions
Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ISO C++ resources