std::ranges::merge
(例如)返回包含合并范围结束的一组迭代器,显然,但也包含两个输入范围的结束。 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.
返回输入范围的结尾有什么意义?
最佳答案
我想引用亚历山大·斯捷潘诺夫的话:
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?
该算法计算了其输入范围的结束,这可能不一定是计算成本低的事情,而且这可能是用户拥有的有用信息,因此它应该只返回它。
例如,您的输入范围可能是一个以空字符结尾的字符串,带有一个前哨,它是一个检查字符是否为
'\0'
的谓词。 .该算法可能会做一些工作,但在此过程中也有效地计算了 strlen
.如果用户正在对字符串做进一步的工作,这可能是有用的信息!更一般地说,返回迭代器意味着采用迭代器/哨兵对的算法现在可以有效地将该范围升级为迭代器/迭代器对。
关于C++ 为什么受约束的算法(例如 std::ranges::merge)也返回输入范围的结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68486391/