liveBook · Manning

Lower_bound

As explained in Learn C++ by Example

lower_bound is a map member function or standard algorithm that returns the first position whose element is greater than or equal to a specified value.

lower_bound returns the first position whose element is greater than or equal to a queried value. Map, set, and multiset provide member functions; std::lower_bound also works with ordered elements such as a sorted vector. section 7.2.2

Use the result to:

  • Test whether a value exists by comparing lower_bound with upper_bound: matching positions mean the value is absent. section 7.2.2
  • Work through all values for a multimap key by using the iterator range returned by equal_range. section 7.2.3
  • Find an insertion position without checking every earlier element in a sorted sequence. section 7.2.2

Searching a sorted vector

For {1, 2, 4, 5, 6, 7}, querying 3 makes lower_bound point to 4, the first element not less than 3. equal_range returns both bounds together.

Listing 7.8 Finding an overlapping word more efficiently
std::pair<std::string, int> find_overlapping_word(std::string word,
    const std::map<std::string, std::string>& dictionary)
{
    size_t offset = 1;
    while (offset < word.size())
    {
        auto stem = word.substr(offset);
        auto [lb, ub] = dictionary.equal_range(stem);        #1
        if (lb != dictionary.end() &&
                stem == lb->first.substr(0, stem.size()))    #2
        {
            return {lb->first, offset};                      #3
        }
        ++offset;
    }
    return {"", -1};
}

A word-overlap function uses equal_range on a dictionary to locate a matching stem while avoiding potentially checking every key. section 7.2.2

How Learn C++ by Example covers it

How deep it goes
Explains bounds, absence testing, equal_range, and a dictionary application, but does not detail the algorithm’s internals.
Examples
Demonstrates a sorted integer vector, multimap key ranges, and dictionary word-overlap lookup.
What it assumes
Assumes ordered elements and iterators while introducing boundary comparisons and equal_range-based lookup.
What you can do after
Apply it via C++ standard-library algorithms and container members to locate insertion positions and lookup ranges.
How it connects
Connects lower_bound with upper_bound, equal_range, std::map, std::set, std::multiset, std::multimap, and sorted vectors.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.