Deduplication and sorting appear in some form in most interview sets, and <algorithm> is why C++ engineers rarely hand-write either: the library versions are correct, heavily optimized, and O(n log n) where it matters (lesson 8-4). Reaching for std::sort instead of writing a loop is a professional habit, not laziness.
set: membership and dedup
std::set<T> stores each value at most once, kept sorted (std::unordered_set is the hashed cousin, like Python's set):
#include <set> std::set<int> seen; seen.insert(5); seen.insert(5); // ignored, already present seen.count(5) // 1 seen.count(7) // 0 seen.size() // 1
Iterating a set visits values in sorted order, so "unique + sorted" is one container away.
The algorithm library
<algorithm> provides functions that work on any container via begin/end iterator pairs (lesson 8-3):
#include <algorithm> std::vector<int> v = {4, 1, 3}; std::sort(v.begin(), v.end()); // 1 3 4 std::sort(v.begin(), v.end(), std::greater<int>()); // 4 3 1 std::reverse(v.begin(), v.end()); std::max_element(v.begin(), v.end()) // ITERATOR to the largest, * it std::min_element(v.begin(), v.end()) std::find(v.begin(), v.end(), 3) // iterator to first 3, or v.end() if absent std::count(v.begin(), v.end(), 3) // how many 3s std::min(a, b); std::max(a, b); // for two plain values
std::sort runs in O(n log n) and also sorts strings and pairs (by first, then second) out of the box. Note the * on max_element's result: algorithms return iterators, dereference to get the value.
Code exercise · cpp
Run this algorithms sampler on one vector.
Custom sort orders: lambdas
std::sort orders by < by default. To sort by any other rule, you pass a comparison function, and the idiomatic way to write one inline is a lambda — an anonymous function defined right where it is used. Syntax: [](parameters) { body } (the leading [] is what marks it as a lambda).
std::vector<std::string> words = {"kiwi", "fig", "banana"}; std::sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) { return a.size() < b.size(); // true when a should come first }); // fig kiwi banana — shortest first
The comparator receives two elements and returns true when the first must come before the second. Note the parameters are const std::string& — lesson 4-2's cheap read-only pass, because the comparator runs O(n log n) times. Sorting by length, by second pair member, or descending are all one lambda away, and this exact pattern is everywhere in interview solutions.
Code exercise · cpp
Run the length sort. Then change the comparator to sort LONGEST first and predict the output before re-running.
Quiz
std::find(v.begin(), v.end(), 99) returns what when 99 is NOT in the vector?
Code exercise · cpp
Your turn. Read 6 integers and print each distinct value once, in sorted order, one per line. A std::set does both jobs at once. Input is `4 2 4 1 2 4`, so the output is 1, then 2, then 4.