Learn C++ · 13/15

The STL: Algorithms, Iterators, and Lambdas

7 min read

Welcome back, developer! 🚀

In the previous modules, you learned how to store data using containers like std::vector and std::map. But storing data is only half the battle. You need to sort it, search it, modify it, and filter it.

In the old days of C (and early C++), we wrote for loops for everything.

  • Want to find a number? Write a loop.
  • Want to sort? Write a nested loop (and pray you didn't mess up the indices).
  • Want to count even numbers? Another loop.

This led to WET (Write Everything Twice) code and bugs.

Enter the Standard Template Library (STL). It separates data (Containers) from operations (Algorithms) using a bridge called Iterators.

This module is about writing less code that does more work. Let's get professional. 💼


1. Iterators: The Bridge Between Containers and Algorithms

The Problem

Imagine you have a std::vector (which works like an array) and a std::list (which works like a linked list).

  • To access vector elements, you use v[i].
  • To access list elements, you have to traverse pointers (node->next).

If you want to write a function that prints any container, you don't want to write two separate functions. You want a uniform way to say "give me the next item," regardless of whether the data is contiguous in memory or scattered like crumbs on a bedsheet.

The Solution: Iterators

An Iterator is an object that points to an element in a range of elements. It behaves very much like a pointer. It decouples the algorithm from the container.

The standard way to navigate data in C++ is asking the container for the beginning and the end.

Under the Hood

  • .begin(): Returns an iterator pointing to the first element.
  • .end(): Returns an iterator pointing one past the last element. (Note: It does not point to the last element. It points to the theoretical slot after the list ends).

💻 Hands-on: The "Old School" vs. Modern Way

cpp
#include <iostream>
#include <vector>
#include <map>

int main() {
    std::vector<int> numbers = {10, 20, 30, 40};

    // 1. Explicit Iterator (The "Old" Way)
    // std::vector<int>::iterator is the type. It's long and ugly.
    std::cout << "Explicit Iterator:\n";
    for (std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) {
        // We 'dereference' the iterator with * to get the value, just like a pointer
        std::cout << *it << " "; 
    }
    std::cout << "\n";

    // 2. The 'auto' keyword (The Modern Standard)
    // The compiler knows what type .begin() returns. Let it do the work.
    std::cout << "Auto Iterator:\n";
    for (auto it = numbers.begin(); it != numbers.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << "\n";
    
    // 3. Range-based for loop (Syntactic Sugar)
    // Under the hood, this actually uses iterators (.begin() and .end())!
    std::cout << "Range-based loop:\n";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << "\n";

    return 0;
}

🧠 Industry Insight: While range-based loops (for(int i : nums)) are cleaner for printing, you still need explicit iterators (numbers.begin()) when using Algorithms like Sort or Find.


2. Common Algorithms: Sorting, Searching, and Counting

The Problem

You need to sort a list of 10,000 user IDs. You could write a Bubble Sort or Quick Sort manually.

  • Risk: You might implement it with O(N2)O(N^2) complexity instead of O(Nlog⁡N)O(N \log N).
  • Risk: You might make an off-by-one error and crash the program.

The Solution: <algorithm>

The STL provides battle-tested, highly optimized algorithms. They typically take a range defined by two iterators: [start, end).

You must include the header:

cpp
#include <algorithm>

A. Sorting (std::sort)

Sorts elements in ascending order by default.

cpp
std::vector<int> v = {4, 2, 5, 1, 3};

// Sort the entire vector
std::sort(v.begin(), v.end()); 
// v is now {1, 2, 3, 4, 5}

// Sort only the first 3 elements
std::sort(v.begin(), v.begin() + 3);

🔥 Fact: std::sort usually implements Introsort, a hybrid of QuickSort, HeapSort, and Insertion Sort. It detects if QuickSort is performing poorly and switches strategies automatically. It is frighteningly fast.

B. Searching (std::find)

Looks for a value. Returns an iterator to the first occurrence. If not found, it returns .end().

cpp
auto it = std::find(v.begin(), v.end(), 3);

if (it != v.end()) {
    std::cout << "Found: " << *it << std::endl;
} else {
    std::cout << "Not found (We reached the end)" << std::endl;
}

C. Counting (std::count)

Counts how many times a value appears.

cpp
int occurrences = std::count(v.begin(), v.end(), 5);

3. Transforming Data with std::transform

The Problem

You have a vector of prices, and you need to apply a tax to every single item. Or you have a string in lowercase, and you need to convert the whole thing to uppercase.

You could write a loop, but that mixes the logic (adding tax) with the mechanics (looping through arrays).

The Solution: std::transform

This algorithm applies a function to a range of elements and stores the result either in the same place (in-place) or a new container.

Syntax:
std::transform(InputBegin, InputEnd, OutputBegin, Operation)

💻 Hands-on: String Conversion

cpp
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

int addTax(int val) {
    return val * 1.1; // 10% tax
}

int main() {
    // Example 1: Math operation
    std::vector<int> prices = {100, 200, 300};
    std::vector<int> final_prices(3); // Make sure output has space!

    std::transform(prices.begin(), prices.end(), final_prices.begin(), addTax);

    // Example 2: String to Upper (In-place)
    std::string s = "hello freecodecamp";
    
    // ::toupper is a standard C function
    std::transform(s.begin(), s.end(), s.begin(), ::toupper);
    
    std::cout << s; // "HELLO FREECODECAMP"
    return 0;
}

⚠️ Warning: The OutputBegin iterator must point to a container that already has enough space allocated. If you write to an empty vector using .begin(), you will cause a Segmentation Fault. Use std::back_inserter if you want to push to a new, empty vector.


4. Lambda Expressions: Anonymous Inline Functions

The Problem

Look at the addTax function above. It's defined globally. We used it once.
In real projects, you might need custom sorting logic (e.g., sort users by age, then by name). creating a named function compareUsersByAgeAndThenName for every tiny operation pollutes your namespace and makes code hard to read because you have to scroll up to find the function definition.

The Solution: Lambdas

A Lambda is a function with no name, written right where you need it. It is the C++ implementation of "Closures."

Syntax Anatomy

cpp
[ capture ] ( parameters ) -> return_type { body }
  1. [] Capture Clause: Access variables from the surrounding scope.
  2. () Parameters: Just like function arguments.
  3. {} Body: The code to execute.

💻 Hands-on: Lambdas in Action

Scenario 1: Custom Sort
Let's sort numbers in descending order.

cpp
#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> nums = {1, 5, 2, 8, 3};

    // Using a Lambda for custom comparison
    // We want a > b for descending order
    std::sort(nums.begin(), nums.end(), [](int a, int b) {
        return a > b; 
    });

    for(int n : nums) std::cout << n << " "; // 8 5 3 2 1
}

Scenario 2: The Capture Clause []
What if we want to filter numbers greater than a variable threshold? The lambda is isolated—it can't see the variable threshold unless we "capture" it.

cpp
int threshold = 3;
std::vector<int> nums = {1, 5, 2, 8, 3};

// [=] means "capture all local variables by value" (read-only copy)
// [&] means "capture all local variables by reference" (can modify original)
int count = std::count_if(nums.begin(), nums.end(), [threshold](int n) {
    return n > threshold;
});

std::cout << count << " numbers are greater than " << threshold;

Industry Standard Usage

Lambdas are heavily used in Modern C++ (C++11 and beyond) for:

  1. Threading: Passing work to a background thread.
  2. Callbacks: UI Event handling (e.g., "On button click, do this").
  3. STL Algorithms: As seen above.

🧠 Interesting Fact

C++ Lambdas are actually just syntactic sugar. When you write a lambda, the compiler secretly creates a class with an overloaded operator() and creates an instance of it. You are writing Object-Oriented code without realizing it! 🥸


Summary Checklist

  • ✅ Iterators are smart pointers (.begin(), .end()) that abstract container navigation.
  • ✅ Algorithms (sort, find, transform) save time and reduce bugs.
  • ✅ Lambdas ([](){}) allow you to write quick, throwaway functions directly inside algorithm calls.

🔗 References & Further Reading

Now, go refactor that for loop! 🛠️

Challenge

You are tasked with managing an inventory of products using the C++ Standard Template Library. You will use STL algorithms and lambda expressions to sort, query, and transform the data.

Inside the main function, working with the provided inventory vector of Product structs, complete the following tasks in order:

  1. Sort the Inventory: Use std::sort and a lambda expression to reorder the inventory vector. The products should be sorted by their price in descending order (most expensive to least expensive).

  2. Count Electronics: Use std::count_if and a lambda predicate to count how many products belong to the "Electronics" category. Store this count in the electronicsCount variable.

  3. Apply a Discount: Create a new std::vector<double> named discountedPrices. Use std::transform and std::back_inserter to populate this new vector. For each product in the (now sorted) inventory, calculate a 10% discount (multiply the price by 0.9) and add the result to discountedPrices.

  4. Find a Product: Use std::find_if and a lambda expression to locate the product with an id of 102. The resulting iterator should be stored in the foundIt variable.

Expected result

Your code should produce the following output to the console:

apache
Number of electronic products: 3
Discounted prices: 1080, 720, 135, 67.5, 13.5
Found product (ID 102): Smartphone
cpp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.