Codectionary / Developer documentation / C++

C++ std::lower_bound searches

lower_bound locates the first element not less than a target in a range partitioned for the same ordering. A sorted vector is a common input. This example requires C++11 or later.

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';
}
  1. 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

Specifications & further reading