[英]Shouldn't lower_bound return an iterator pointing to end()?
I am trying to understand lower_bound
better.我试图更好地理解
lower_bound
。 I have the code below:我有以下代码:
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> data = { -1,0,3,5,9,12 };
auto lower = std::lower_bound(data.begin(), data.end(), -2);
if (lower != data.end())
std::cout << *lower << " at index " << std::distance(data.begin(), lower);
else
std::cout << "not found";
std::cout << '\n';
}
Note that this is just a sample code modified from cppreference.com.请注意,这只是从 cppreference.com 修改的示例代码。 Per the documentation there:
根据那里的文档:
Returns an iterator pointing to the first element in the range [first, last) that is not less than (ie greater or equal to) value, or last if no such element is found .
返回一个迭代器,该迭代器指向范围 [first, last) 中不小于(即大于或等于)值的第一个元素,如果没有找到这样的元素,则返回 last 。
Given that the element I am looking for -2
isn't present in the vector data
, I expect lower_bound
to set lower==data.end()
.鉴于我正在寻找的元素
-2
不存在于矢量data
中,我希望lower_bound
设置为lower==data.end()
。 However, what I get is:但是,我得到的是:
-1 at index 0
-1 在索引 0
instead.反而。 Could someone please explain why ?
有人可以解释为什么吗?
Many thanks!非常感谢!
The easiest way to remember how std::lower_bound
works is that it will return an iterator to the place where an item should be inserted to retain the sorted order.记住
std::lower_bound
如何工作的最简单方法是,它将一个迭代器返回到应该插入项目的位置以保留排序顺序。 In your case that would be the beginning of the sequence.在您的情况下,这将是序列的开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.