Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Ranges algorithms and std algorithms

Tags:

c++

c++20

Many standard library algorithms have two versions in C++20: one in the std namespace and another one in the std::ranges namespace with the same name. For example, std::ranges::count and std::count are both are used to count the number of elements that satisfy a predicate.

Why are there two versions of these algorithms?

like image 609
Harry Avatar asked Feb 03 '23 14:02

Harry


1 Answers

The Ranges functionality adds C++20 concepts to iterators and ranges, and it constrains the definition of its algorithms and the like to those concepts. However, the C++20 concepts have different requirements from the C++17 named requirements. Usually, types which fulfilled the C++17 requirements will fulfill the C++20 concept equivalents, but not in all cases1. And while it is usually easy enough to update your own code to be valid for C++20 concepts, it would still break backwards compatibility for user-written iterators to just stop compiling in C++20.

So instead of imposing constrained algorithms on the user, they created new algorithms that you can choose to use instead. Thus, no code breakage.

1: Also, because C++17's requirements were never actually checked by anything, it was really easy to accidentally write an iterator that didn't entirely implement their requirements. The algorithms you use could just not actually use the the functionality you didn't implement, thus giving the appearance that you implemented what you needed to. This is especially true if you didn't test the code against more than one standard library implementation. If C++20 started checking your iterators, it would suddenly break your technically-broken-yet-functional code.

like image 65
Nicol Bolas Avatar answered Feb 11 '23 11:02

Nicol Bolas