liveBook · Manning

Associative container

As explained in Learn C++ by Example

An associative container is a data structure that organizes elements by keys or ordered values rather than by positional indexes.

An associative container organizes elements around keys instead of positional indexes. An std::map stores key-value pairs in key order, providing dictionary-style lookup. Related containers include std::multimap, which permits duplicate keys, and std::set, which stores ordered keys without mapped values. section 7.0 section 7.4

Use associative containers to:

  • Query or insert map elements with operator[], while using at when a failed query must not create an element. section 7.4
  • Represent multiple values with std::pair, std::tuple, or structured bindings. section 7.4
  • Search ordered containers efficiently with lower_bound, upper_bound, and equal_range. section 7.2.2

Answer Smash

A dictionary maps clue words to definitions for a word-overlap game. Searching with equal_range helps find a word whose beginning matches a later stem; a multimap can retain several entries for one key. section 7.0 section 7.2.2

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};
}

Inspect a complete function that combines equal_range with prefix checking to locate an overlapping dictionary word. section 7.2.2

How Learn C++ by Example covers it

How deep it goes
Explains maps, multimaps, sets, access behavior, complexity, and bound searches, stopping short of full implementation internals.
Examples
Demonstrates hardcoded dictionaries, overlapping words, bound searches, and random dictionary selection.
What it assumes
Builds from earlier use of vectors while introducing dictionaries, pairs, tuples, and structured bindings.
What you can do after
Apply associative containers to build dictionary lookups and improve ordered searches.
How it connects
Connects std::map with std::multimap, std::set, std::pair, std::tuple, structured bindings, and string_view.

Also explained in

Compare how 2 books explain associative container →

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.