c++ - 为什么 lower_bound 和 upper_bound 的谓词版本不一致地传递迭代器值?

标签 c++ algorithm stl

upper_bound 的二进制谓词中,迭代器值作为第二个参数传递,而在 lower_bound 中,迭代器值作为第一个参数传递。

这里的推理是什么?在编写自己的二元谓词时,我是否记得这个细节有关系吗?


注意 我的引用是 www.cplusplus.com(有人告诉我这可能不是最好的引用)并且我通过查看 STL 中的实现来确认它VC++ 附带的库。

最佳答案

这是故意的。原因是您可以对两种算法使用相同的比较器。考虑描述。 lower_bound :

Returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value.

upper_bound :

Returns an iterator pointing to the first element in the range [first, last) that is greater than value.

考虑标准比较器是 < .为了仅使用 < 来实现这两种算法需要 !(elem < value)对于一个和value < elem对于另一个。参数顺序的倒置直接由此而来。

不过,这不应影响您实现 Comparator 的方式。

关于c++ - 为什么 lower_bound 和 upper_bound 的谓词版本不一致地传递迭代器值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28485437/

相关文章:

c++ - OpenCV:如何创建 .vec 文件以与 opencv_traincascade 一起使用

c# - PssCreateSnapshot - 访问被拒绝的奇怪情况

algorithm - Picopala算法实现

algorithm - 最小化连接到多条边的顶点数的生成树?

algorithm - 为什么贝尔曼福特算法中的 |V|-1 次迭代可以保证最短路径?

c++ - 从嵌套迭代的列表中删除

c++ - 如何将 std::vector 转换为 std::span?

c++ - 优化 volatile 堆栈变量的存储/构造是否合法?

c++ - 惯用STL : Iterating over a list and inserting elements

c++ - 为什么 iterator::end( ) 是非静态成员而不类似于 string::npos?