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
- Lesson 11
Represent multi-field records with struct.
- Lesson 12
Write a comparator that handles equality without using <=.
- Lesson 13
Use lower_bound for the first position at or above the target.
- Lesson 14
Use upper_bound for the first position strictly above the target.
- 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.