The STL: Containers and Algorithms
💻 C++Use vector, map, set and standard algorithms instead of writing everything yourself.
0 of 9 completed
The Standard Template Library gives you tested containers and algorithms. Knowing it well is the difference between clever code and maintainable code.
By the end of this lesson you can:
- Choose a container.
- Use sort, find and accumulate.
- Write a lambda for an algorithm.
Containers
std::vector— ordered, fast to iterate.std::map— sorted key-value pairs.std::unordered_map— fast lookups without order.std::set— unique sorted values.
Algorithms
Include <algorithm> and <numeric> for sorting, searching and summing.
#include <algorithm>
#include <numeric>
#include <vector>
std::vector<int> scores = {88, 74, 91, 65};
std::sort(scores.begin(), scores.end());
int total = std::accumulate(scores.begin(), scores.end(), 0);
auto found = std::find(scores.begin(), scores.end(), 91);
if (found != scores.end()) {
std::cout << "Found 91\n";
}Lambdas
A lambda is an inline function. Use it with algorithms to express intent without a separate named function.
auto passing = std::count_if(scores.begin(), scores.end(),
[](int score) { return score >= 70; });
std::cout << passing << " students passed\n";Tip Prefer standard algorithms over hand-written loops. They are tested, optimised and easier for another developer to read.
Practice
- Sort a vector of names alphabetically.
- Count how many scores are below 50.
- Use a map to count word frequencies.
Hands-on exercise
Given a vector of scores:
1. Sort it.
2. Print the highest and lowest.
3. Count how many are at least 70 using count_if and a lambda.
Recap
Choose the container that matches the access pattern, and use standard algorithms with lambdas for collection work.
Example
#include <algorithm>
#include <numeric>
#include <vector>
std::vector<int> scores = {88, 74, 91, 65};
std::sort(scores.begin(), scores.end());
int total = std::accumulate(scores.begin(), scores.end(), 0);
auto found = std::find(scores.begin(), scores.end(), 91);
if (found != scores.end()) {
std::cout << "Found 91
";
}
Exercises
Exercise 1. Class statistics
Medium
Given a vector of scores:
1. Sort it.
2. Print the highest and lowest.
3. Count how many are at least 70 using count_if and a lambda.
1. Sort it.
2. Print the highest and lowest.
3. Count how many are at least 70 using count_if and a lambda.
C++
exercise-1.txt
Output
Expected Output
Lowest 52, Highest 91, 70 or above: 3
Lesson Nav
Course contents
C++ Course
0/9 lessons completed
- 1 Your First C++ Program Tutorial
- 2 Variables, Types and Input Tutorial
- 3 Conditions and Loops Tutorial
- 4 Functions and Parameters Tutorial
- 5 Arrays and Vectors Tutorial
- 6 Pointers and References Tutorial
- 7 Classes and Objects Tutorial
- 8 The STL: Containers and Algorithms Tutorial
- 9 Project: A Console Grade Book Project
Exercises
Exercise 1 Class statistics