Menu
Coddy logo textTech

STL Algorithms

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 73 of 104.

STL algorithms are template functions that operate on ranges defined by iterators. They're found in the <algorithm> and <numeric> headers and work with any container that provides compatible iterators.

std::sort arranges elements in ascending order by default:

#include <algorithm>
#include <vector>

std::vector<int> nums = {5, 2, 8, 1};
std::sort(nums.begin(), nums.end());
// nums: {1, 2, 5, 8}

std::find searches for a value and returns an iterator to the first match, or end() if not found:

auto it = std::find(nums.begin(), nums.end(), 5);
if (it != nums.end()) {
    std::cout << "Found at index: " << (it - nums.begin());
}

std::transform applies an operation to each element and stores results in a destination range:

std::vector<int> doubled(nums.size());
std::transform(nums.begin(), nums.end(), doubled.begin(),
               [](int x) { return x * 2; });
// doubled: {2, 4, 10, 16}

std::accumulate from <numeric> combines all elements into a single value:

#include <numeric>

int sum = std::accumulate(nums.begin(), nums.end(), 0);
// sum: 16 (1 + 2 + 5 + 8)

These algorithms accept iterator ranges rather than containers directly, making them flexible enough to work on partial ranges or different container types with the same code.

challenge icon

Challenge

Easy

Let's build a score analyzer that processes a collection of numbers using STL algorithms. You'll create utility functions that demonstrate how sort, find, transform, and accumulate work together to analyze data.

You'll organize your code across two files:

  • ScoreAnalyzer.h: Define utility functions that use STL algorithms to process vectors of integers.

    Create a function called sortScores that takes a std::vector<int>& and sorts it in ascending order using std::sort.

    Create a function called findScore that takes a const std::vector<int>& and an int target value. Use std::find to search for the target. If found, return the index (distance from begin). If not found, return -1.

    Create a function called applyBonus that takes a const std::vector<int>& and an int bonus amount. Use std::transform to create and return a new vector where each score has the bonus added to it.

    Create a function called calculateAverage that takes a const std::vector<int>& and returns the average as a double. Use std::accumulate to compute the sum, then divide by the size.

    Create a function called printVector that takes a const std::vector<int>& and prints all elements separated by spaces, followed by a newline.

  • main.cpp: Read six inputs (each on a separate line):
    1. First score (integer)
    2. Second score (integer)
    3. Third score (integer)
    4. Fourth score (integer)
    5. A score to search for (integer)
    6. A bonus amount to apply (integer)

    Create a vector with the four scores and demonstrate the algorithms:

    1. Print Original: followed by the vector contents
    2. Sort the scores and print Sorted: followed by the sorted vector
    3. Search for the target score in the sorted vector. If found, print Found <value> at index <index>. If not found, print <value> not found
    4. Apply the bonus to the sorted scores and print With bonus: followed by the new vector
    5. Calculate and print the average of the original sorted scores (before bonus) as Average: <value> with one decimal place

For example, with inputs 75, 90, 60, 85, 85, and 5:

Original: 75 90 60 85 
Sorted: 60 75 85 90 
Found 85 at index 2
With bonus: 65 80 90 95 
Average: 77.5

With inputs 100, 80, 95, 70, 50, and 10:

Original: 100 80 95 70 
Sorted: 70 80 95 100 
50 not found
With bonus: 80 90 105 110 
Average: 86.2

Remember to include <algorithm> for sort, find, and transform, and <numeric> for accumulate. Use std::fixed and std::setprecision(1) from <iomanip> for formatting the average.

Cheat sheet

STL algorithms are template functions from <algorithm> and <numeric> that operate on ranges defined by iterators.

std::sort arranges elements in ascending order:

#include <algorithm>
#include <vector>

std::vector<int> nums = {5, 2, 8, 1};
std::sort(nums.begin(), nums.end());
// nums: {1, 2, 5, 8}

std::find searches for a value and returns an iterator to the first match, or end() if not found:

auto it = std::find(nums.begin(), nums.end(), 5);
if (it != nums.end()) {
    std::cout << "Found at index: " << (it - nums.begin());
}

std::transform applies an operation to each element and stores results in a destination range:

std::vector<int> doubled(nums.size());
std::transform(nums.begin(), nums.end(), doubled.begin(),
               [](int x) { return x * 2; });
// doubled: {2, 4, 10, 16}

std::accumulate from <numeric> combines all elements into a single value:

#include <numeric>

int sum = std::accumulate(nums.begin(), nums.end(), 0);
// sum: 16 (1 + 2 + 5 + 8)

These algorithms work with iterator ranges, making them flexible for partial ranges or different container types.

Try it yourself

#include <iostream>
#include <vector>
#include <iomanip>
#include "ScoreAnalyzer.h"

using namespace std;

int main() {
    // Read six inputs
    int score1, score2, score3, score4;
    int searchTarget, bonusAmount;
    
    cin >> score1;
    cin >> score2;
    cin >> score3;
    cin >> score4;
    cin >> searchTarget;
    cin >> bonusAmount;
    
    // TODO: Create a vector with the four scores
    
    // TODO: Print "Original:" followed by the vector contents
    
    // TODO: Sort the scores and print "Sorted:" followed by the sorted vector
    
    // TODO: Search for the target score in the sorted vector
    // If found, print "Found <value> at index <index>"
    // If not found, print "<value> not found"
    
    // TODO: Apply the bonus to the sorted scores and print "With bonus:" followed by the new vector
    
    // TODO: Calculate and print the average of the sorted scores (before bonus)
    // Use fixed and setprecision(1) for formatting
    // Print as "Average: <value>"
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming