Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++why do constrained algorithms (e.g. std::ranges::merge) also return the end of the input ranges?

std::ranges::merge (for example) returns a bundle of iterators containing the end of the merged range, obviously, but also the end of the two input ranges. Cppreference says (https://en.cppreference.com/w/cpp/algorithm/ranges)

Additionally, the return types of most algorithms have been changed to return all potentially useful information computed during the execution of the algorithm.

What is the point of returning the end of the input ranges?

like image 201
le migou Avatar asked Jul 22 '21 14:07

le migou


Video Answer


1 Answers

I'd like to quote Alexander Stepanov:

When writing code, it’s often the case that you end up computing a value that the calling function doesn’t currently need. Later, however, this value may be important when the code is called in a different situation. In this situation, you should obey the law of useful return: A procedure should return all the potentially useful information it computed.

To get back to the question:

What is the point of returning the end of the input ranges?

The algorithm calculated the end of its input range, which may not necessarily be a cheap thing to calculate, and that may be useful information for the user to have, so it should just return it.

For example, your input range might be a null-terminated string with a sentinel that is a predicate that checks if the character is '\0'. The algorithm might do some work, but effectively in the process also computes strlen. That may be useful information to have back if the user is doing further work with the string!

More generally, returning an Iterator means that an algorithm that takes an Iterator/Sentinel pair now can effectively upgrade that range to an Iterator/Iterator pair.

like image 91
Barry Avatar answered Oct 07 '22 05:10

Barry