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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 44: Ranges Library (C++20) | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

Lesson 44 of 45

·C++

Lesson 44: Ranges Library (C++20)

14 min

Course progress98%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • View‑based lazy evaluation
  • Composable adapters (`filter`, `transform`, etc.)
  • Range‑based algorithms (C++20)
  • Performance benefits of lazy pipelines

Ranges Library (C++20)

The 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.


Common views

  • std::views::filter
  • std::views::transform
  • std::views::take
  • std::views::drop
  • std::views::reverse

Example: Filtering and transforming a vector

std::vector<int> numbers = {1, 2, 3, 4, 5, 6};
auto evenSquares = numbers
    | std::views::filter([](int n){ return n % 2 == 0; })
    | std::views::transform([](int n){ return n * n; });
for (int v : evenSquares) {
    std::cout << v << ' ';
}
std::cout << '\
';

The above pipeline never creates a temporary container; each element is processed on‑the‑fly.

Using std::ranges::sort

std::vector<std::string> words = {\"apple\", \"banana\", \"cherry\"};
std::ranges::sort(words, std::greater{}); // sort descending
for (const auto& w : words) std::cout << w << ' ';
std::cout << '\
';

Tip: When an algorithm accepts a range (e.g., std::ranges::find), you can pass a view directly without calling .begin()/.end().


<Alert type="warning">Views hold references to the underlying container; ensure the container outlives the view to avoid dangling references.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 43: Concepts (C++20)Continue to lesson 45Lesson 45: Modules and Final Project OverviewBack to C++ Course curriculum