C++ · Module 14 · Lesson 31 min read

Searching & Checking Algorithms

Linear searches — O(n), any order

AlgorithmReturns
std::find(b, e, value)iterator to first match, or e
std::find_if(b, e, pred)first element where pred is true
std::find_if_notfirst where pred is false
std::count(b, e, value), std::count_if(b, e, pred)how many
std::any_of, std::all_of, std::none_ofbool
std::search(b, e, sb, se)first occurrence of a subsequence
std::adjacent_findfirst pair of equal neighbours
std::min_element, std::max_element, std::minmax_elementiterators to extremes
std::mismatch, std::equalcompare two ranges

all_of on an empty range is true; any_of is false.

Binary searches — O(log n), range must be sorted ⚠️

AlgorithmReturns
std::binary_search(b, e, v)bool: present?
std::lower_bound(b, e, v)first element ≥ v
std::upper_bound(b, e, v)first element > v
std::equal_range(b, e, v)pair of the two above → all copies of v

lower_bound is the workhorse: insertion point for keeping a vector sorted, "first transaction on or after date X", counting values in a range (upper_bound(hi) - lower_bound(lo)).

Ranges versions (C++20)

std::ranges::find(v, x), std::ranges::any_of(v, pred), std::ranges::max(v) — pass the container directly, and use projections:

c
std::ranges::find(users, "Asha", &User::name);
std::ranges::max(expenses, {}, &Expense::amount);

Remember

Containers like set, map, unordered_map have their own faster find/contains members — use those instead of std::find on them.

Example

C++
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

struct User {
    std::string name;
    int age;
    bool premium;
};

int main() {
    std::vector<int> balances = { 1200, -50, 3400, 0, 870, -300 };
    std::cout << std::boolalpha;
    std::cout << "any negative? " << std::any_of(balances.begin(), balances.end(), [](int b) { return b < 0; }) << '\n';
    std::cout << "all under 5000? " << std::all_of(balances.begin(), balances.end(), [](int b) { return b < 5000; }) << '\n';
    std::cout << "none over 10000? " << std::none_of(balances.begin(), balances.end(), [](int b) { return b > 10000; }) << '\n';
    std::cout << "negative count: " << std::count_if(balances.begin(), balances.end(), [](int b) { return b < 0; }) << '\n';

    auto first_neg = std::find_if(balances.begin(), balances.end(), [](int b) { return b < 0; });
    std::cout << "first negative at index " << (first_neg - balances.begin()) << '\n';
    auto [lo, hi] = std::minmax_element(balances.begin(), balances.end());
    std::cout << "min " << *lo << ", max " << *hi << '\n';

    std::vector<int> sorted = { 100, 250, 250, 250, 400, 900, 1500 };
    std::cout << "binary_search 400? " << std::binary_search(sorted.begin(), sorted.end(), 400) << '\n';
    auto lb = std::lower_bound(sorted.begin(), sorted.end(), 250);
    auto ub = std::upper_bound(sorted.begin(), sorted.end(), 250);
    std::cout << "250 appears " << (ub - lb) << " times, first at index " << (lb - sorted.begin()) << '\n';
    std::cout << "values in [200, 1000]: "
              << std::upper_bound(sorted.begin(), sorted.end(), 1000) - std::lower_bound(sorted.begin(), sorted.end(), 200) << '\n';
    auto insert_at = std::lower_bound(sorted.begin(), sorted.end(), 500);
    sorted.insert(insert_at, 500);                        // stays sorted
    std::cout << "after inserting 500:";
    for (int x : sorted) std::cout << ' ' << x;
    std::cout << '\n';

    std::vector<User> users = { { "Asha", 24, true }, { "Ravi", 31, false }, { "Sita", 19, true } };
    if (auto it = std::ranges::find(users, "Ravi", &User::name); it != users.end())
        std::cout << "found Ravi, age " << it->age << '\n';
    const User& oldest = std::ranges::max(users, {}, &User::age);
    std::cout << "oldest: " << oldest.name << ", premium users: "
              << std::ranges::count_if(users, &User::premium) << '\n';
    return 0;
}

/* Output:
any negative? true
all under 5000? true
none over 10000? true
negative count: 2
first negative at index 1
min -300, max 3400
binary_search 400? true
250 appears 3 times, first at index 1
values in [200, 1000]: 5
after inserting 500: 100 250 250 250 400 500 900 1500
found Ravi, age 31
oldest: Ravi, premium users: 2
*/