Interview Q&A · C++ · 10 questions in this topic
STL Algorithms & Idioms — C++ Interview Q&A
Thinking in algorithms — sorting, searching, remove-erase, lambdas with algorithms, and complexity guarantees. Part of STL Containers & Algorithms · 213 questions in the C++ bank.
Why should you use STL algorithms instead of hand-written loops?
Answer
Algorithms name intent (sort, find_if, transform vs an anonymous for), are reviewed and optimized once, compose with lambdas and execution policies, and eliminate off-by-one and invalidation mistakes. They also parallelize (C++17 execution policies) where hand loops would need rewriting.
Modern guidance: no raw loops for named operations — reach for the algorithm first.
Example
#include <algorithm> bool any_neg(const std::vector<int>& v) { return std::any_of(v.begin(), v.end(), [](int x) { return x < 0; }); }
💡 Name intent plus fewer bugs is the complete justification; parallel policies are the bonus.
What is the complexity of `std::sort` and is it stable?
Answer
std::sort averages O(n log n) (introsort: quicksort switching to heapsort past depth limits, insertion sort for tiny runs) and is not stable — equal elements may reorder. stable_sort preserves equal-element order at O(n log n) with O(n) extra memory (or O(n log²n) without). partial_sort handles top-k efficiently.
Sort requires random-access iterators, which is why list has its own member sort.
Example
std::vector<int> v{3,1,2}; std::sort(v.begin(), v.end()); // not stable std::stable_sort(v.begin(), v.end()); // stable, extra memory
How does binary search (`lower_bound`, `upper_bound`, `binary_search`) work in STL?
Answer
They operate on sorted ranges: lower_bound finds the first element not less than the value, upper_bound the first greater, binary_search just reports presence, equal_range returns both. All are O(log n) on random-access iterators (O(n) steps on weaker iterators) and require the same ordering used for sorting.
Calling them on unsorted data is silently wrong — no diagnostic.
Example
std::vector<int> v{1, 2, 2, 5}; auto lo = std::lower_bound(v.begin(), v.end(), 2); // first 2 bool has = std::binary_search(v.begin(), v.end(), 5);
What does `std::remove` actually do? Why the erase-remove idiom?
Answer
remove compacts surviving elements forward and returns the new logical end — it does not shrink the container (it cannot: it only sees iterators). erase then truncates the tail. The pair is needed because algorithms cannot change container size, only containers can.
C++20 std::erase handles both steps for standard containers in one call.
Example
std::vector<int> v{1, 2, 3, 2}; v.erase(std::remove(v.begin(), v.end(), 2), v.end()); // {1, 3} // C++20: std::erase(v, 2); // same, one call
💡 Algorithms rearrange, containers resize — that sentence explains the whole idiom.
How do custom comparators work with sort and ordered containers?
Answer
They impose a strict weak ordering (irreflexive, transitive, antisymmetric-definite): comp(a,b) means a goes before b. Lambdas, functors or function pointers all work; ordered containers bake the comparator into the type (std::map<K,V,Comp>), so heterogeneous lookup needs transparent comparators (is_transparent).
A comparator that violates strictness (e.g. <= instead of <) corrupts trees and sorts with undefined behavior.
Example
std::sort(v.begin(), v.end(), [](const auto& a, const auto& b) { return a.score > b.score; // descending: strict < on reversed args });
What are C++20 ranges and views?
Answer
Ranges operate on whole ranges instead of iterator pairs, with constraints enforced by concepts (clear errors) and composable lazy views (filter, transform, take) that cost nothing until iterated. Views are non-owning, so they must not outlive their data — the same lifetime rule as string_view.
They turn iterator-pair boilerplate into readable pipelines: data | filter | transform.
Example
#include <ranges> #include <vector> std::vector<int> v{1,2,3,4,5}; auto evens = v | std::views::filter([](int x){ return x % 2 == 0; }); for (int x : evens) { /* 2, 4 */ }
How do `std::find`, `std::count` and `std::any_of` differ?
Answer
find returns the first matching iterator (or end), count returns the occurrence tally, any_of/all_of/none_of return booleans over a predicate. Prefer the boolean algorithms when only existence matters — they short-circuit and state intent.
For associative containers, prefer the member find/count (hash/tree lookup) over the generic linear algorithms.
Example
auto it = std::find(v.begin(), v.end(), 7); bool present = (it != v.end()); bool fast = my_set.count(7) > 0; // member: O(log n) / O(1)
💡 Member lookup for associative containers, generic algorithms for sequences — that split is the whole answer.
What is `std::move` algorithm vs `std::move` cast? (The name collision.)
Answer
std::move (one argument, <utility>) casts to an rvalue reference — it moves nothing by itself. std::move algorithm (three iterators, <algorithm>) moves each element of a range into a destination — it actually relocates. The shared name confuses because one is a cast and the other is a bulk relocation loop.
Read the arity: one argument is the cast, three arguments is the algorithm.
Example
#include <utility> #include <algorithm> std::string s = "x"; auto r = std::move(s); // cast: s now valid-but-unspecified std::vector<std::string> a{"p","q"}, b(2); std::move(a.begin(), a.end(), b.begin()); // algorithm: relocates elements
What are execution policies (`std::execution`) and when are they unsafe?
Answer
Policies (sequenced, parallel, parallel_unsequenced, unsequenced) let algorithms run multi-threaded or vectorized. They are unsafe when element operations have data races, take locks in conflicting orders, throw (terminate for some policies), or depend on order — vectorized policies additionally forbid branches that break SIMD assumptions.
Use them for independent elementwise work over large inputs; verify associativity-independence first.
Example
#include <execution> // parallel transform over independent elements: std::transform(std::execution::par, v.begin(), v.end(), out.begin(), fn);
How do you use lambdas effectively with STL algorithms?
Answer
Capture minimally and explicitly ([&total] not [&] in stored code), take parameters as const auto& to avoid copies, mark mutation-free lambdas for parallel policies, and keep predicates pure (no side effects) so reordering stays valid.
Init-capture ([n = v.size()]) moves expensive state in; mutable enables by-value modification when genuinely needed.
Example
int threshold = 5; int n = std::count_if(v.begin(), v.end(), [threshold](int x) { return x > threshold; }); // explicit capture
💡 Explicit minimal captures plus const-ref parameters is the review-proof lambda style.
Recommended resourcesAffiliate links · may earn us a commission