Lesson 33 of 45
C++Lesson 33: Algorithms (sort, find, transform, etc.)
13 min
Course progress73%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 33 of 45
C++13 min
Keep these ideas in mind as you work through the lesson.
The <algorithm> header provides a wealth of generic algorithms that operate on iterator ranges. They are designed to work with any container that supplies the appropriate iterator category.
std::sort, std::stable_sort, std::partial_sort.std::find, std::binary_search, std::lower_bound, std::upper_bound.std::transform, std::replace, std::remove, std::unique.std::accumulate, std::inner_product, std::reduce (C++17).struct Person {
std::string name;
int age;
};
std::vector<Person> people = { {\"Bob\",30}, {\"Alice\",25}, {\"Eve\",35} };
// Sort by age ascending using a lambda comparator
std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) {
return a.age < b.age;
});
for (const auto& p : people) {
std::cout << p.name << \" (\" << p.age << \")\
\";
}
Tip: When possible, use the range‑based overloads from
<algorithm>(C++20) likestd::ranges::sortfor clearer syntax.
<Alert type="info">Many algorithms invalidate iterators after they modify the container (e.g., std::remove does not actually erase elements). Pair them with vector::erase when needed.