Concepts / Ordering Functions and Comparison in Containers

Ordering Functions and Comparison in Containers

The cost of a map lookup is $O(\log(n))$, where n is the number of elements, and the source notes that a map with 1,000,000 elements needs only about 20 comparisons and indirections.

  • Programming

Predicting the Cost of One Lookup

Suppose you already store your data in a map and you ask it to find one element. How much work does that search take? This article answers that question and then asks what it would take for a container to be even faster for lookups, and what that container gives up in exchange.

What do you think happens?

A map holds 1,000,000 elements. Roughly how many comparisons and indirections does one lookup need?

  • About 1,000,000, because every entry might have to be checked

  • About 500,000, because on average half the entries must be checked

  • About 20

Reveal answer
Answer:

About 20

The source states that a map with 1,000,000 elements needs only about 20 comparisons and indirections to find an element. The map does not inspect a million entries; the cost grows logarithmically with the number of elements.

Tracing a Search Through a Million Elements

A map finds an element by comparison. At each step it uses an ordering function, such as the less-than operator, to decide which direction to move in as it searches. Each comparison rules out a large share of the candidates that could still hold the key, so the search shrinks quickly. The source does not spell out every internal detail of this process, so the halving pattern below is an illustration of how a logarithmic cost behaves, not a literal trace of any particular implementation.

Step 11,000,000 candidatesStep 2500,000 candidatesStep 3250,000 candidatesStep 4125,000 candidatesStep 10about 1,000 candidatesStep 20about 1 candidatecompare, discard about halfcompare, discard about halfcompare, discard about halfcontinue halvingcontinue halving
How the number of candidates still in play shrinks as a comparison-based lookup proceeds through a 1,000,000-element map. Each step discards a large share of what remains, so the candidate count falls to about one after roughly twenty steps.

Read the diagram from top to bottom. The first comparison leaves about half of the million candidates in play, the second leaves about a quarter, and so on. The search does not visit each entry in turn; it removes large blocks of candidates with each comparison. Because the count is cut repeatedly, the number of steps needed is small even when the collection is very large.

Why the Logarithm Keeps the Count Small

The cost of a map lookup is written $O(\log(n))$, where $n$ is the number of elements in the map. The notation describes growth. The number of steps grows with the size of the map, but much more slowly than the size itself. A cost of this form does not promise a fixed number of steps; it describes how the count changes as the collection grows.

Formula

The source's own example uses this calculation. For a map with 1,000,000 elements, a lookup performs about 20 comparisons and indirections. The logarithm base 2 of one million is about 20, which matches that stated figure. The useful habit is to read the cost as a growth rate: multiplying the collection size by a thousand adds only about ten more steps in this model, which is why logarithmic lookup is attractive for large maps.

Two Routes from a Key to an Element

The two containers differ in the route a lookup takes. Both routes start from a key and end at an element, but the middle step is different. A map searches by comparison: it uses an ordering function to relate keys and move through the search. An unordered_map takes a hashed route that avoids comparison using an ordering function. The source notes that in many cases a hashed lookup can do better than a comparison-based lookup.

keykeycompare usingordering functionfor example less-thanhashed lookupno ordering function neededelementabout log(n) stepselementoften faster, notguaranteedsearch by comparisonnarrow until foundhash the keyreach element
The map's lookup repeatedly compares against an ordering to narrow the search, while the unordered_map's lookup avoids that ordering step and moves toward a candidate location directly from the key.

Notice what the diagram leaves out. It does not show the internal layout of either container, because the source does not describe how a hashed container arranges its elements. The comparison focuses on the lookup route alone: one container searches by comparing against an ordering, and the other avoids that ordering requirement entirely.

Why the Name Says Unordered

Definition

The standard-library hashed containers are called unordered because they do not require an ordering function. The name describes a requirement that is absent, not a messy or random layout that a programmer must cope with.

A map needs an ordering function such as the less-than operator to decide how its elements relate and how to search them. An unordered_map does not need that ordering function at all. This is why the word unordered should be read as a statement about what the container does not require. It is a claim about the absence of an ordering requirement, and it should not be read as a promise that the container is disorganized.

Choosing Between map and unordered_map

The source gives a clear decision rule: if the goal is efficient lookup, consider a hashed lookup as an alternative to comparison using an ordering function, since it can be better in many cases. The flowchart below turns that rule into a sequence of questions. The question about sorted order is drawn from the meaning of the word unordered, which tells you the hashed container does not provide an ordering requirement.

Need efficientlookup by keyMust elements bewalked in sorted keyorder?mapordering function isrequiredunordered_maphashed lookup, often fasteryesno
A decision path for choosing between an ordered map and an unordered_map when the main need is efficient lookup by key.

Worked Decision Using the Source's Numbers

Worked example

Estimating Lookup Cost for a Large Map

A program stores 1,000,000 elements in a map and performs one lookup by key. Use the source's cost model to estimate the work, then decide whether an unordered_map is worth considering.

  1. 1
    Identify the cost model

    A map lookup costs $O(\log(n))$, where $n$ is the number of elements. Here $n = 1{,}000{,}000$.

  2. 2
    Estimate the step count

    The source states that a map of this size needs about 20 comparisons and indirections, which matches $\log_2(1{,}000{,}000) \approx 20$.

  3. 3
    Compare against the collection size

    The map does not inspect a million entries. The step count is small relative to the size of the collection, which is what logarithmic growth means.

  4. 4
    Apply the decision rule

    If the goal is efficient lookup and the program does not need elements walked in sorted key order, the source's guidance suggests considering a hashed lookup through unordered_map, since it can be better in many cases.

  5. 5
    Check the tendency, not a guarantee

    The source describes unordered_map as faster in many cases, but this is a tendency and not a guarantee. Measure for the actual workload before relying on it.

Result

A map lookup on a million elements takes about 20 comparisons and indirections, which is already efficient. An unordered_map is a reasonable alternative to consider when sorted traversal is not needed, but the choice should be confirmed for the real program.

Mistakes to Avoid

  • Common mistake

    Reading O(log(n)) as a fixed number of steps

    Why it fails

    The notation describes how the cost grows with the number of elements. The figure of about 20 comparisons applies to the source's example of 1,000,000 elements, not to every map.

    Do this instead

    Treat the cost as a growth rate and use the source's example only as one concrete data point.

  • Common mistake

    Believing unordered means the elements are stored in a random or messy way

    Why it fails

    The name refers to the absence of a requirement for an ordering function. It does not describe a disorderly layout that a programmer must manage.

    Do this instead

    Read unordered as meaning that the container does not need an ordering function to operate.

  • Common mistake

    Assuming unordered_map is always faster than map

    Why it fails

    The source says unordered_map is faster than map in many cases, but this is a tendency and not a guarantee.

    Do this instead

    Choose based on the need for efficient lookup and then measure the workload before assuming a speed advantage.

  • Common mistake

    Choosing unordered_map when sorted key order matters

    Why it fails

    A hashed container does not rely on an ordering function, so it is not the right choice when the program must walk elements in sorted key order.

    Do this instead

    Use map when ordered traversal is needed, and consider unordered_map when the main requirement is fast lookup.

Practice: Tracing a Decision

MEDIUM

A program needs to look up customer records by customer ID many times per second. It never needs to list the customers in ID order. Using the source's guidance, which container would you consider first, and what would you still want to check before committing to that choice? Explain your reasoning in terms of the lookup route and the ordering requirement.

Hints
  • Ask whether the program needs ordered traversal. The statement that it never lists customers in ID order is the key clue.
  • Recall that the source frames a hashed lookup as a better option in many cases, but not in every case.

Key Takeaways

  • A map lookup costs $O(\log(n))$, so the step count grows much more slowly than the number of elements; the source's example of 1,000,000 elements needs about 20 comparisons and indirections.
  • A map finds elements by comparison using an ordering function such as the less-than operator, while a hashed lookup avoids that ordering requirement.
  • The standard-library hashed containers are called unordered because they do not require an ordering function, not because their elements are disorganized.
  • unordered_map is often faster for lookup than map, but this is a tendency and not a guarantee, so consider it when sorted key order is not needed and confirm the choice for the real workload.

Related concepts

More concepts starting with O