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 39 of 45 · C++

Lesson 44: Ranges Library (C++20)

Duration: 14 min

Ranges Library (C++20)\n\nThe Ranges library unifies algorithms and containers under a common view‑based approach. Views are lazy, composable adapters that transform a range without materialising intermediate containers.\n\n---\n\n## Common views\n- std::views::filter\n- std::views::transform\n- std::views::take\n- std::views::drop\n- std::views::reverse\n\n## Example: Filtering and transforming a vector\ncpp\nstd::vector<int> numbers = {1, 2, 3, 4, 5, 6};\nauto evenSquares = numbers\n | std::views::filter([](int n){ return n % 2 == 0; })\n | std::views::transform([](int n){ return n * n; });\nfor (int v : evenSquares) {\n std::cout << v << ' ';\n}\nstd::cout << '\\n';\n\n\nThe above pipeline never creates a temporary container; each element is processed on‑the‑fly.\n\n## Using std::ranges::sort\ncpp\nstd::vector<std::string> words = {\"apple\", \"banana\", \"cherry\"};\nstd::ranges::sort(words, std::greater{}); // sort descending\nfor (const auto& w : words) std::cout << w << ' ';\nstd::cout << '\\n';\n\n\n> Tip: When an algorithm accepts a range (e.g., std::ranges::find), you can pass a view directly without calling .begin()/.end().\n\n---\n\n<Alert type="warning">Views hold references to the underlying container; ensure the container outlives the view to avoid dangling references.

Previous: Lesson 43: Concepts (C++20)Next: Lesson 45: Modules and Final Project Overview