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

标签 c++ c++20 std-ranges

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/

相关文章:

c++ - 我们真的需要将范围适配器隐式转换为 bool 值吗?

c++ - g++:在涉及多个翻译单元的情况下RVO如何工作

c++ - Qt:强制QDockWidget的大小

c++ - 当我编译代码时出现此错误无法在 C++ 中打开文件 X11/Xlib.h

c++ - 是否可以在没有宏的情况下在 C++20 中实现一次日志?

c++ - 为什么没有引入std::ranges::?

c++ - 查找字符在标准输入文本中出现的次数

c++ - 为什么 C++20 的要求表达式的行为不符合预期?

c++ - 为什么我不能将 char* 静态转换为 std::byte*?

c++ - 是否有任何标准功能可用于创建以容器为 mapped_type 的 map 的平面 View ?