STL Overview & Philosophy
Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 70 of 104.
The Standard Template Library (STL) is a collection of template-based classes and functions that provide common data structures and algorithms. Built on the template concepts you've learned, the STL embodies a powerful design philosophy: separate data storage from data manipulation.
The STL is organized around three core components that work together:
| Component | Purpose | Examples |
|---|---|---|
| Containers | Store collections of objects | vector, map, set |
| Iterators | Provide access to container elements | Input, output, random access |
| Algorithms | Perform operations on data | sort, find, transform |
The key insight is that algorithms don't know about containers directly - they work through iterators. This means a single sort algorithm works with vectors, arrays, and any container that provides the right iterator type:
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> nums = {5, 2, 8, 1, 9};
std::sort(nums.begin(), nums.end());
for (int n : nums) {
std::cout << n << " ";
}
// Output: 1 2 5 8 9
}This separation means you can mix and match - use any algorithm with any compatible container without writing new code. The STL provides battle-tested, optimized implementations so you can focus on solving problems rather than reinventing common data structures.
Challenge
EasyLet's build a simple data processing system that demonstrates the STL philosophy of separating containers, iterators, and algorithms. You'll create a utility module that works with STL components and a main program that shows how these pieces fit together.
You'll create two files:
DataProcessor.h: Define utility functions that work with STL containers through iterators, demonstrating the STL's design philosophy.Create a function called
printVectorthat takes astd::vector<int>&and prints all elements separated by spaces, followed by a newline. Use iterators (begin()andend()) to traverse the container.Create a function called
sortAndPrintthat takes astd::vector<int>&, sorts it usingstd::sort, then prints the sorted elements separated by spaces followed by a newline.Create a function called
findElementthat takes astd::vector<int>&and anintvalue to search for. Usestd::findto locate the element. If found, printFound: <value>. If not found, printNot found: <value>.Create a function called
getSumthat takes astd::vector<int>&and returns the sum of all elements. You can use a simple loop with iterators for this.main.cpp: Read inputs and demonstrate how STL components work together.Read five inputs (each on a separate line):
- First integer
- Second integer
- Third integer
- Fourth integer
- A value to search for
Create a
std::vector<int>and add the first four integers to it. Then demonstrate the STL philosophy by:- Printing
Original:followed by callingprintVector - Printing
Sorted:followed by callingsortAndPrint - Calling
findElementwith the search value - Printing
Sum: <result>usinggetSum
For example, with inputs 5, 2, 8, 1, and 8:
Original: 5 2 8 1
Sorted: 1 2 5 8
Found: 8
Sum: 16With inputs 10, 30, 20, 40, and 15:
Original: 10 30 20 40
Sorted: 10 20 30 40
Not found: 15
Sum: 100Notice how your functions work with the vector through iterators, and how std::sort and std::find operate on any container that provides the right iterator type. This is the power of the STL's design — algorithms are decoupled from containers, connected only through iterators.
Cheat sheet
The Standard Template Library (STL) is a collection of template-based classes and functions providing common data structures and algorithms. It separates data storage from data manipulation.
The STL has three core components:
| Component | Purpose | Examples |
|---|---|---|
| Containers | Store collections of objects | vector, map, set |
| Iterators | Provide access to container elements | Input, output, random access |
| Algorithms | Perform operations on data | sort, find, transform |
Algorithms work through iterators, not directly with containers. This allows a single algorithm to work with any compatible container:
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> nums = {5, 2, 8, 1, 9};
// Sort using iterators
std::sort(nums.begin(), nums.end());
// Traverse using iterators
for (int n : nums) {
std::cout << n << " ";
}
// Output: 1 2 5 8 9
}Common iterator methods:
begin()- returns iterator to first elementend()- returns iterator to position after last element
Common STL algorithms:
std::sort(begin, end)- sorts elements in rangestd::find(begin, end, value)- searches for value in range
Try it yourself
#include <iostream>
#include <vector>
#include "DataProcessor.h"
using namespace std;
int main() {
// Read five integers from input
int num1, num2, num3, num4, searchValue;
cin >> num1;
cin >> num2;
cin >> num3;
cin >> num4;
cin >> searchValue;
// TODO: Create a vector and add the first four integers to it
// TODO: Print "Original: " and call printVector
// TODO: Print "Sorted: " and call sortAndPrint
// TODO: Call findElement with the search value
// TODO: Print "Sum: " followed by the result of getSum
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