C++ STL Algorithms: Mastering std::sort, Search, Transform & Reductions

The <algorithm> and <numeric> headers offer over 100 highly optimized algorithms for data manipulation. Professional C++ developers adhere to the principle: "Know your algorithms and avoid writing manual raw loops."

Core Algorithms in Action

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

int main() {
    std::vector<int> data = {45, 12, 85, 32, 89, 39, 69, 44};

    // 1. Sort in ascending order: O(N log N)
    std::sort(data.begin(), data.end());

    // 2. Binary search: O(log N)
    bool found = std::binary_search(data.begin(), data.end(), 69);
    std::cout << "69 found: " << std::boolalpha << found << "\n";

    // 3. Accumulate sum: O(N)
    int total = std::accumulate(data.begin(), data.end(), 0);
    std::cout << "Total Sum: " << total << "\n";

    // 4. Transform: Square every number
    std::vector<int> squared(data.size());
    std::transform(data.begin(), data.end(), squared.begin(), [](int n) {
        return n * n;
    });

    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What sorting algorithm does std::sort use in C++?

std::sort uses 'Introsort' (Introductory Sort), a hybrid algorithm that begins with Quicksort for speed, switches to Heapsort if the recursion depth exceeds 2*log(N) to prevent worst-case O(N^2), and finishes with Insertion Sort for small partitions, guaranteeing O(N log N) worst-case time.

Q2. What is the prerequisite for calling std::binary_search?

The container elements MUST be sorted beforehand! Calling std::binary_search on an unsorted range results in Undefined Behavior or incorrect false results.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

STL Iterators

Passing iterator ranges (begin, end) to algorithms.

Lambda Expressions

Writing inline predicate lambdas for algorithms.

C++20 Ranges

Modern pipeline syntax for STL algorithms.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!