Library contents

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

  1. Start with Sorted values 1, 3, 5
  2. Do this Find the first value at least 2
  3. Result 3
One is too small. Three is the first value that satisfies the condition.

Syntax

C++ 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.

First output line1
lesson.cpp
#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;
}
Output
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

Advertisements

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?

Given4 · 9 · 15 · 22 | seek 15
Worked result2

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?

Given3 · 6 · 10 | seek 3
Worked result0