C++20 introduces the ranges library. A range is a group of items that can be iterated over. It should provide a begin
iterator and an
end
sentinel. All the existing STL containers are ranges.
This new library makes working with the STL library much more powerful by introducing range adaptors and much less verbose by introducing a
constrained version of most algorithms in the namespace std::ranges
. Before the ranges library, you had to specify the begin
and end
iterators when calling the STL algorithms, even when you want to iterate over the whole container.
This rule focuses on making your code less verbose and more readable by suggesting range-based over iterator-based algorithms when convenient.
Noncompliant code example
auto printEven = [](auto i) {
if (i % 2 == 0) {
std::cout << i;
}
};
void f1(const std::vector<int>& v) {
std::for_each(v.begin(), v.end(), printEven); // Noncompliant
}
Compliant solution
auto printEven = [](auto i) {
if (i % 2 == 0) {
std::cout << i;
}
};
void f2(const std::vector<int>& v) {
std::ranges::for_each(v, printEven); // Compliant
}