Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

c++ - Difference between Ranges algorithms and std algorithms

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...