Courses/C++/STL Algorithm Mastery

    Lesson 18 • Advanced

    STL Algorithm Mastery

    Master the STL algorithm library: sort, find, transform, accumulate, partition, and the remove-erase idiom.

    What You'll Learn

    • Sorting with custom comparators
    • find, find_if, count_if, binary_search
    • transform and accumulate for data processing
    • partition, remove-erase, and unique

    Why Use STL Algorithms?

    Writing your own loops is fine for simple tasks, but STL algorithms are battle-tested, optimised, and self-documenting. When you see sort(), you know exactly what happens. When you see a 15-line loop, you have to read every line.

    STL algorithms operate on iterator ranges — a pair of begin() and end() iterators. This means the same algorithm works with vectors, arrays, deques, and any container that provides iterators.

    Transform & Accumulate

    Process data with transform, accumulate, min/max, and for_each

    Try it Yourself »
    C++
    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <numeric>
    using namespace std;
    
    int main() {
        vector<int> prices = {1299, 2499, 599, 3999, 899};
        
        // transform — apply function to each element
        cout << "=== transform ===" << endl;
        vector<double> dollars(prices.size());
        transform(prices.begin(), prices.end(), dollars.begin(),
            [](int cents) { return cents / 100.0; });
        
        cout << "Prices in dollars: ";
        for (double d : dollars) cout << "$" <
    ...

    Partition, Remove & Unique

    Rearrange, filter, and deduplicate elements efficiently

    Try it Yourself »
    C++
    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    void printVec(const string& label, const vector<int>& v) {
        cout << label << ": ";
        for (int n : v) cout << n << " ";
        cout << endl;
    }
    
    int main() {
        // partition — rearrange so predicate-true elements come first
        cout << "=== partition ===" << endl;
        vector<int> nums = {1, 8, 3, 6, 2, 9, 4, 7, 5};
        
        auto pivotIt = partition(nums.begin(), nums.end(), [](int n) {
            return n % 2 == 0;  /
    ...

    Common Mistakes

    ⚠️ binary_search on unsorted data: binary_search requires a sorted range. On unsorted data, results are undefined.

    ⚠️ Forgetting erase after remove: remove() doesn't shrink the container — it returns the new logical end. You must call erase() to actually remove elements.

    ⚠️ Invalidating iterators: Modifying a container while iterating with algorithms can invalidate iterators. Use the remove-erase idiom instead.

    Pro Tips

    💡 Use ranges (C++20): ranges::sort(vec) is cleaner than sort(vec.begin(), vec.end()).

    💡 nth_element for partial sorts: If you only need the top-N elements, nth_element is O(n) instead of O(n log n).

    💡 Combine algorithms: Chain sortuniqueerase for a fast deduplicate, or partition → process each half separately.

    📋 Quick Reference

    AlgorithmPurposeComplexity
    sortSort rangeO(n log n)
    find / find_ifLinear searchO(n)
    binary_searchSorted searchO(log n)
    transformApply functionO(n)
    accumulateReduce/foldO(n)
    partitionSplit by predicateO(n)

    Lesson Complete!

    You now command the most important STL algorithms for sorting, searching, transforming, and filtering data. Next: Advanced Containers — internals of vector, list, map, unordered_map, and deque.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service