Lesson 18 of 20Practical Modern C++28 min

Algorithms, Iterators, and Lambdas

STL algorithms perform common operations on container ranges. Iterators identify positions in those ranges, and lambda expressions provide small pieces of behaviour directly where they are used.

Sorting a Vector

sort algorithm
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> marks = {78, 92, 65, 88, 74};
    sort(marks.begin(), marks.end());

    for (int mark : marks)
        cout << mark << " ";

    return 0;
}

Finding with a Lambda

find_if and lambda
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> marks = {45, 52, 68, 81, 90};

    auto result = find_if(marks.begin(), marks.end(),
        [](int mark)
        {
            return mark >= 80;
        });

    if (result != marks.end())
        cout << "First mark of 80 or above: " << *result << endl;

    return 0;
}

Reading the Range

begin() points to the first element. end() points just beyond the last element. Most STL algorithms process the half-open range [begin, end).

Practice task

Sort a vector of names alphabetically, then use find() to search for one name.

Lesson Summary

Use sort, find_if, iterators, and lambda expressions with STL containers.