New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› C++› The STL: Containers and Algorithms

The STL: Containers and Algorithms

💻 C++

Use vector, map, set and standard algorithms instead of writing everything yourself.

Lesson 8 of 9 Tutorial
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

  1. Sort a vector of names alphabetically.
  2. Count how many scores are below 50.
  3. 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.
C++ exercise-1.txt
Expected Output
Lowest 52, Highest 91, 70 or above: 3

Lesson Nav

Lesson sections