Skip to content
C++ Basics: Find the First Drop in a Sequence

C++ Basics: Find the First Drop in a Sequence

November 4, 2026

Apply std::adjacent_find with a predicate to detect a decreasing neighboring pair.

Prepare a scratch directory

Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.

Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save this as adjacent-find-drop-demo.cpp:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

int main()
{
    const std::vector<int> readings{10, 12, 12, 9, 14};
    const auto drop = std::adjacent_find(readings.begin(), readings.end(),
        [](int previous, int next) { return previous > next; });
    if (drop != readings.end()) {
        std::cout << "Drop at " << std::distance(readings.begin(), drop)
                  << ": " << *drop << " -> " << *std::next(drop) << '\n';
    } else {
        std::cout << "No drop\n";
    }
}

Compile and run it. The program runs only after compilation succeeds:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic adjacent-find-drop-demo.cpp -o adjacent-find-drop-demo &&
./adjacent-find-drop-demo

Observed output:

Drop at 2: 12 -> 9

Read the result

The equal pair 12, 12 does not satisfy the predicate. The next pair, 12, 9, does. The returned iterator points to the first member of that pair, at index 2. A successful result therefore has a following element available.

Apply it carefully

This searches neighbors rather than all possible pairs. An empty or one-element range has no adjacent pair and returns end(). Keep the end check before using either value. Use greater-than-or-equal only if equal readings should also be considered failures; that is a different monotonicity rule.

The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.

Clean up

Remove only the source and executable created here, then return to the starting directory:

rm -- adjacent-find-drop-demo.cpp adjacent-find-drop-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect its remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on