C++ STL ALGORITHMS ARCHITECTURE: SORTING, SEARCHING, MUTATING & NUMERIC OPERATIONS

Master the third pillar of the C++ Standard Template Library (STL): non-modifying algorithms (`std::find`, `std::count`), modifying algorithms (`std::sort`, `std::transform`), numeric reductions (`std::accumulate`), and lambda expression integration.

📌 What are STL Algorithms in C++?

The STL Algorithms library (defined in the and headers) provides over 100 high-performance, template-based functions that operate on ranges of elements defined by iterators. Rather than writing manual raw loops for sorting, searching, filtering, or transforming data, developers rely on these standardized algorithms. Because they are decoupled from container implementations via iterators, a single algorithm like std::sort works identically on vectors, raw arrays, or deques while achieving optimal hardware-level performance.

1. Non-Modifying Algorithms (`std::find`, `std::count`, `std::all_of`)
Non-modifying algorithms inspect container elements without altering their values or order. They accept iterator ranges and return search results or boolean evaluations.
C++ (non_modifying_algorithms.cpp)
#include 
#include 
#include 

int main() {
    std::vector sensorReadings = {45, 12, 78, 12, 90, 33};

    // 1. std::find: Locate first occurrence of value 78
    auto it = std::find(sensorReadings.begin(), sensorReadings.end(), 78);
    if (it != sensorReadings.end()) {
        std::cout << "Found value 78 at index: " << std::distance(sensorReadings.begin(), it) << "\n";
    }

    // 2. std::count: Count occurrences of value 12
    int count12 = std::count(sensorReadings.begin(), sensorReadings.end(), 12);
    std::cout << "Value 12 appears " << count12 << " time(s).\n";

    // 3. std::all_of: Check if all readings are positive (> 0)
    bool allPositive = std::all_of(sensorReadings.begin(), sensorReadings.end(), [](int n) {
        return n > 0;
    });
    std::cout << "Are all sensor readings positive? " << (allPositive ? "YES" : "NO") << "\n";

    return 0;
}
Output: Found value 78 at index: 2 Value 12 appears 2 time(s). Are all sensor readings positive? YES
2. Modifying & Sorting Algorithms (`std::sort`, `std::reverse`, `std::remove`)
Modifying algorithms alter the order or content of elements within ranges. std::sort executes IntroSort (guaranteeing $O(N \log N)$ worst-case performance), while rearranging routines reorder elements in-place.
C++ (modifying_algorithms.cpp)
#include 
#include 
#include 

int main() {
    std::vector scores = {42, 15, 99, 88, 23};

    // 1. std::sort: Ascending order
    std::sort(scores.begin(), scores.end());
    std::cout << "Sorted Ascending: ";
    for (int s : scores) std::cout << s << " ";
    std::cout << "\n";

    // 2. Custom sorting using lambda (Descending order)
    std::sort(scores.begin(), scores.end(), [](int a, int b) {
        return a > b;
    });
    std::cout << "Sorted Descending: ";
    for (int s : scores) std::cout << s << " ";
    std::cout << "\n";

    // 3. std::reverse: Reverse element order
    std::reverse(scores.begin(), scores.end());
    std::cout << "Reversed Vector: ";
    for (int s : scores) std::cout << s << " ";
    std::cout << "\n";

    return 0;
}
Output: Sorted Ascending: 15 23 42 88 99 Sorted Descending: 99 88 42 23 15 Reversed Vector: 15 23 42 88 99
3. Transforming & Numeric Algorithms (`std::transform`, `std::accumulate`)
Transformation algorithms apply functions across ranges to generate new sequences, while numeric algorithms (defined in ) compute reductions, inner products, and prefix sums.
C++ (transform_accumulate.cpp)
#include 
#include 
#include 
#include 

int main() {
    std::vector baseValues = {1, 2, 3, 4, 5};
    std::vector squaredValues(baseValues.size());

    // 1. std::transform: Square each element
    std::transform(baseValues.begin(), baseValues.end(), squaredValues.begin(), [](int x) {
        return x * x;
    });

    std::cout << "Squared Values: ";
    for (int val : squaredValues) std::cout << val << " ";
    std::cout << "\n";

    // 2. std::accumulate: Compute sum of squared values
    int totalSum = std::accumulate(squaredValues.begin(), squaredValues.end(), 0);
    std::cout << "Total Sum of Squares: " << totalSum << "\n";

    return 0;
}
Output: Squared Values: 1 4 9 16 25 Total Sum of Squares: 55
4. Real-Time Example: Enterprise Employee Salary Pipeline
A production-grade real-time example: filtering, transforming, and computing payroll statistics across an employee salary vector using STL algorithms and lambdas.
C++ (payroll_pipeline.cpp)
#include 
#include 
#include 
#include 

int main() {
    std::cout << "============================================\n";
    std::cout << "💼 ENTERPRISE PAYROLL PROCESSING PIPELINE\n";
    std::cout << "============================================\n";

    std::vector salaries = {55000.0, 120000.0, 75000.0, 45000.0, 95000.0};

    // 1. Sort salaries descending to find highest earners
    std::sort(salaries.begin(), salaries.end(), std::greater());

    std::cout << "Salaries (Highest to Lowest): ";
    for (double s : salaries) std::cout << "$" << s << " ";
    std::cout << "\n";

    // 2. Apply a 10% performance bonus inflation to all salaries
    std::transform(salaries.begin(), salaries.end(), salaries.begin(), [](double salary) {
        return salary * 1.10;
    });

    // 3. Compute total payroll expenditure using std::accumulate
    double totalPayroll = std::accumulate(salaries.begin(), salaries.end(), 0.0);
    double averageSalary = totalPayroll / salaries.size();

    std::cout << "Total Payroll After 10% Bonus: $" << totalPayroll << "\n";
    std::cout << "Average Inflated Salary: $" << averageSalary << "\n";
    std::cout << "============================================\n";

    return 0;
}
Output: ============================================ 💼 ENTERPRISE PAYROLL PROCESSING PIPELINE ============================================ Salaries (Highest to Lowest): $120000 $95000 $75000 $55000 $45000 Total Payroll After 10% Bonus: $423500 Average Inflated Salary: $84700 ============================================
5. Summary Reference Matrix: STL Algorithms Overview
A comprehensive reference summary categorizing essential STL algorithms, headers, and time complexities.
C++ STL Algorithms Reference Matrix
C++ STL ALGORITHMS REFERENCE MATRIX:

┌─────────────────────┬───────────────────────────┬───────────────────────────┬─────────────────────────────────┐
│ Algorithm Category  │ Header                    │ Common Functions          │ Time Complexity                 │
├─────────────────────┼───────────────────────────┼───────────────────────────┼─────────────────────────────────┤
│ Non-Modifying       │ ``                        │ `find`, `count`, `all_of` │ O(N)                            │
│ Sorting & Ordering  │ ``                        │ `sort`, `binary_search`   │ O(N log N)                      │
│ Modifying/Mutating  │ ``                        │ `reverse`, `transform`    │ O(N)                            │
│ Numeric Reductions  │ ``                        │ `accumulate`, `inner_product`│ O(N)                         │
├─────────────────────┴───────────────────────────┴───────────────────────────┴─────────────────────────────────┤
│ ENGINEERING BEST PRACTICES:                                                                                   │
│ 1. Always prefer standard STL algorithms over manual raw `for` loops; they express intent clearly and are optimized.│
│ 2. Leverage lambda expressions inline with algorithms to eliminate redundant helper function declarations.    │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
Engineering Best Practice: Combine STL algorithms with lambda expressions to write expressive, concise, and high-performance data processing pipelines.