C++ PROGRAMMING ยท 14 MIN STUDY

STL algorithms, iterators, and lambdas

Use standard algorithms and iterators to search, sort, count, and transform collections.

Learning objectives

  • Explain the role of iterators in the standard library.
  • Use sort, find, and count.
  • Understand iterator ranges as half-open intervals.
  • Write a simple lambda predicate.

Prerequisites: vectors, loops, iterators at a basic level, and lambda syntax introduced in the lesson. Examples use standard algorithms from <algorithm>.

Why algorithms matter

The C++ standard library provides reusable algorithms that work with ranges of elements. Instead of writing a loop for every common task, use a tested algorithm with iterators that identify where the elements begin and end.

C++17
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> values{7, 2, 9, 2, 5};
    std::sort(values.begin(), values.end());
    auto found = std::find(values.begin(), values.end(), 5);
    auto twos = std::count(values.begin(), values.end(), 2);
    std::cout << twos << '\n';
    if (found != values.end()) std::cout << *found << '\n';
}

begin() refers to the first element, while end() refers to the position just after the last element. The range includes the first iterator but excludes the last: [begin, end).

What is an iterator?

An iterator is an object that lets an algorithm move through a sequence and access its elements using a common interface. Different containers provide different iterator capabilities. A vector iterator supports random access; a list iterator does not support jumping directly to an arbitrary index.

Search results and end()

std::find returns an iterator to the first matching element. If there is no match, it returns the end iterator. Never dereference the result until you have checked that it is not equal to end().

Lambdas: small unnamed functions

A lambda expression creates a function object that can be passed to an algorithm. The expression below checks whether a number is even.

auto is_even = [](int value) {
    return value % 2 == 0;
};

You can pass it to std::count_if to count values that satisfy the condition:

int even_count = std::count_if(values.begin(), values.end(), is_even);

Sorting with a comparison rule

std::sort(values.begin(), values.end(),
          [](int left, int right) {
              return left > right;
          });

The comparator must define a strict weak ordering. For ordinary descending integer order, left > right is suitable. Do not write a comparator using >=; a value must not compare as ordered before itself.

Complexity

AlgorithmTypical complexity
findLinear, O(n)
count / count_ifLinear, O(n)
sortO(n log n) comparisons
reverseLinear, O(n)

Common mistakes

  • Dereferencing the end() iterator.
  • Passing iterators from different containers as one range.
  • Using an invalid comparator such as a >= b.
  • Assuming every container supports random-access iterators.
  • Forgetting to include <algorithm>.

Practice

  1. Sort a vector of five numbers in ascending order.
  2. Use find and correctly report when a value is absent.
  3. Use count_if with a lambda to count numbers greater than 10.
  4. Sort a vector of strings by length, and explain your comparator.

Practice solutions

Show worked solutions
  1. Call std::sort(values.begin(), values.end()) after including <algorithm>. The default ordering for integers is ascending.
  2. Store the result of std::find; if it equals values.end(), the value was not found. Otherwise, dereference the iterator.
  3. Use std::count_if(values.begin(), values.end(), [](int value) { return value > 10; }). The lambda returns true for each value that meets the condition.
  4. Use std::stable_sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) { return a.size() < b.size(); }). The comparator orders shorter strings first; stable_sort preserves the original relative order of equal-length strings.

Check your understanding

Why does find return end() when an element is absent?

Answer: The end iterator is the standard marker for the position after the range, so algorithms use it to indicate that no matching element was found.

Summary

Iterators connect containers to algorithms. Learn the half-open range convention, check search results before dereferencing, and use lambdas to express small custom rules.

References