Lessons 11–15 · About 60 min per lesson

Custom sorting and binary-search bounds

Define a sort rule and locate ranges quickly in ordered data.

Lesson breakdown

  1. Lesson 11

    Represent multi-field records with struct.

  2. Lesson 12

    Write a comparator that handles equality without using <=.

  3. Lesson 13

    Use lower_bound for the first position at or above the target.

  4. Lesson 14

    Use upper_bound for the first position strictly above the target.

  5. Lesson 15

    Count a closed interval with both bounds and check duplicates and misses.

Worked example

Timestamps are [2,4,4,7]. Count records in the closed interval [4,6].

How to solve it

lower_bound(4) gives index 1 and upper_bound(6) gives index 3, for a count of 2.

Assignment

Sort timestamps and use two binary searches per closed-interval count. The left endpoint is at most the right.

Check your result

For the example, [4,4] → 2, [5,6] → 0 and [0,7] → 4.