C++ 为什么约束算法(例如 std::ranges::merge)也 return 输入范围的末尾?

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

std::ranges::merge(例如)returns 一束包含合并范围末尾的迭代器,显然,也是两个输入范围的末尾。 Cppreference 说 (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.

返回输入范围的末尾有什么意义?

我想引用 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.

回到问题:

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

该算法计算了其输入范围的末端,这可能不一定是计算成本低的事情,而且对用户来说可能是有用的信息,因此它应该 return 它。

例如,您的输入范围可能是一个以 null 结尾的字符串,带有一个标记,它是一个谓词,用于检查字符是否为 '[=10=]'。该算法可能会做一些工作,但有效地在此过程中还计算 strlen。如果用户正在对字符串做进一步的工作,这可能是有用的信息!

更一般地说,return迭代器意味着采用 Iterator/Sentinel 对的算法现在可以有效地将范围升级到 Iterator/Iterator 对。