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
EasyLet'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
sortScoresthat takes astd::vector<int>&and sorts it in ascending order usingstd::sort.Create a function called
findScorethat takes aconst std::vector<int>&and aninttarget value. Usestd::findto search for the target. If found, return the index (distance from begin). If not found, return-1.Create a function called
applyBonusthat takes aconst std::vector<int>&and anintbonus amount. Usestd::transformto create and return a new vector where each score has the bonus added to it.Create a function called
calculateAveragethat takes aconst std::vector<int>&and returns the average as adouble. Usestd::accumulateto compute the sum, then divide by the size.Create a function called
printVectorthat takes aconst std::vector<int>&and prints all elements separated by spaces, followed by a newline.main.cpp: Read six inputs (each on a separate line):- First score (integer)
- Second score (integer)
- Third score (integer)
- Fourth score (integer)
- A score to search for (integer)
- A bonus amount to apply (integer)
Create a vector with the four scores and demonstrate the algorithms:
- Print
Original:followed by the vector contents - Sort the scores and print
Sorted:followed by the sorted vector - Search for the target score in the sorted vector. If found, print
Found <value> at index <index>. If not found, print<value> not found - Apply the bonus to the sorted scores and print
With bonus:followed by the new vector - 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.5With 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.2Remember 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;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy10STL Overview
STL Overview & PhilosophySTL ContainersIteratorsSTL AlgorithmsFunctors & Lambda ExpressionsRecap - Word Frequency2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container