Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 27 of 45 · C++

Lesson 33: Algorithms (sort, find, transform, etc.)

Duration: 13 min

Algorithms (sort, find, transform, etc.)\n\nThe <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.\n\n---\n\n## Commonly used algorithms\n- Sorting – std::sort, std::stable_sort, std::partial_sort.\n- Searching – std::find, std::binary_search, std::lower_bound, std::upper_bound.\n- Modification – std::transform, std::replace, std::remove, std::unique.\n- Numeric – std::accumulate, std::inner_product, std::reduce (C++17).\n\n---\n\n## Example: Sorting a vector of structs by a member field\ncpp\nstruct Person {\n std::string name;\n int age;\n};\nstd::vector<Person> people = { {\"Bob\",30}, {\"Alice\",25}, {\"Eve\",35} };\n// Sort by age ascending using a lambda comparator\nstd::sort(people.begin(), people.end(), [](const Person& a, const Person& b) {\n return a.age < b.age;\n});\nfor (const auto& p : people) {\n std::cout << p.name << \" (\" << p.age << \")\\n\";\n}\n\n\n> Tip: When possible, use the range‑based overloads from <algorithm> (C++20) like std::ranges::sort for clearer syntax.\n\n---\n\n<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.

Previous: Lesson 32: Map and Unordered MapNext: Lesson 34: Lambda Expressions