C++ Fundamentals

Lesson 09 · 14 min

STL Algorithms You Actually Need

sort, reverse, max/min, lower_bound — interview toolkit.

High-value STL

sort(a.begin(), a.end());
reverse(a.begin(), a.end());
int mx = *max_element(a.begin(), a.end());
int mn = *min_element(a.begin(), a.end());
swap(a[i], a[j]);

lower_bound / upper_bound

On a sorted range: binary search positions. Returns iterator.

accumulate

long long sum = accumulate(a.begin(), a.end(), 0LL);

Use 0LL so the sum type is long long.

Don't memorize all of <algorithm>

Know sort, reverse, max_element, swap, binary search bounds. Rest you can look up later.

Rules to remember

  • sort needs random-access iterators (vector OK).
  • accumulate third arg type controls sum type — use 0LL.
  • lower_bound requires sorted order.
  • prefer clear loops over obscure STL if clarity wins interview.

Check yourself

1. Safe sum of many ints into long long?

Practice what you learned