Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use std::ranges algorithms over regular algorithms?

cppreference states:

The ranges library is an extension and generalization of the algorithms and iterator libraries that makes them more powerful by making them composable and less error-prone.

The library creates and manipulates range views, lightweight objects that indirectly represent iterable sequences (ranges).

It mentions using range views, which are, as cppreference states:

The range concept defines the requirements of a type that allows iteration over its elements by providing an iterator and sentinel that denote the elements of the range.

But from an outside perspective, it just seems like a wrapper of an iterator with a concept. So the main question is:

  • What are the problems with using regular algorithms that the ranges library solves (code examples will be appreciated), and when should you use it?
like image 790
dnl Avatar asked Mar 24 '26 07:03

dnl


2 Answers

The second one will allow you to pipe other operations present only in the ranges header, which is much better for composability:

#include <ranges>
#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    const auto v = std::vector{ 1, 2, 3, 4, 5 };
    const auto is_odd = [](const auto n){ return n % 2 == 1; };
    const auto square = [](const auto n){ return n * n; };
    const auto print = [](const auto n){ std::cout << n << " ";};
    std::ranges::for_each(
        v | std::ranges::views::filter(is_odd) | std::ranges::views::transform(square),
        print); // prints: 1 9 25 
}
like image 81
thebugger Avatar answered Mar 26 '26 20:03

thebugger


what are the problems with using regular iterators that ranges library solves (code examples will be appreciated)?

It might avoid some mistakes with temporary container:

// assuming std::vector<int> compute_vector();

// Following is wrong begin and end refers to different (temporary) containers
const bool KO = std::is_sorted(compute_vector().begin(),
                               compute_vector().end()); // WRONG

// Here all is ok.
const bool OK = std::ranges::is_sorted(compute_vector());
like image 27
Jarod42 Avatar answered Mar 26 '26 21:03

Jarod42