Skip to the page

Templates and the STL · core

Iterators, sort and comparators

Iterators walk through any container with the same code. sort orders a range in O(n log n), and a comparator changes the order, but it must be a strict "less than".

The notes

What you must know

  • A range is [begin, end): begin() is the first element, and end() is one past the last, so it must not be dereferenced. An empty range has begin() == end().
  • vector and string have random access iterators (it + k is O(1)); map, set and list iterators move one step at a time.
  • sort(v.begin(), v.end()) sorts in increasing order with O(n log n) comparisons. It is not stable; stable_sort keeps equal elements in their old order.
  • Descending order: sort(v.begin(), v.end(), greater<int>()), or a lambda [](int a, int b) { return a > b; }.
  • A comparator must be a strict ordering: comp(a, a) must be false. A comparator that uses <= or >= breaks this; the result is undefined behaviour: a wrong order, or even a crash.
  • Sort by marks descending, then name ascending: return a.marks != b.marks ? a.marks > b.marks : a.name < b.name;. pair and tuple already compare the first item, then the second.
  • On a sorted range, lower_bound finds the first element >= x and upper_bound the first element > x, in O(log n). upper_bound minus lower_bound counts the copies of x.
  • Erasing while looping: it = v.erase(it); returns the next valid iterator (vector, map and set all do this). Using the old iterator after erase is undefined.

The red pen

Common traps: mistake → fix

  • Mistake: A comparator with <= works the same as <

    Fix: it breaks the strict ordering and is undefined.

  • Mistake: end() points to the last element

    Fix: it points one past the last.

  • Mistake: std::sort keeps equal elements in their old order

    Fix: use stable_sort for that.

  • Mistake: lower_bound works on any vector

    Fix: the range must be sorted.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you sort a vector in descending order?
  2. Sort students by marks, highest first, and by name when the marks are equal.
  3. Why must a comparator not use <=?
  4. What do lower_bound and upper_bound return? How do you count the copies of x in a sorted vector? What is the cost of binary search and of sorting?
  5. How do you erase elements from a vector while looping over it?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview