简体   繁体   English

即使元素不存在,c ++ stl中的lower_bound也会返回一个迭代器。 怎么避免这个?

[英]lower_bound in c++ stl returns an iterator even when the element is not present. How to avoid this?

With

int arr[]={1,2,3,5,6,7};

using lower_bound(arr,arr+6,4) returns an iterator to 5 . 使用lower_bound(arr,arr+6,4)将迭代器返回到5 How to make sure that it returns an index only when the element is present? 如何确保它仅在元素存在时返回索引?

std::lower_bound is what you want, you just need to add a condition to your check. std::lower_bound就是你想要的,你只需要为你的支票添加一个条件。 To see if 4 is in the array you would just use 要查看4是否在您将使用的数组中

int arr[] = {1,2,3,5,6,7}; 
auto it = std::lower_bound(std::begin(arr), std::end(arr), 4)
if (it != std::end(arr) && *it == 4) // && short circuts so *it == 4 wont be done unless it is valid
    std::cout << "4 found";
else
    std::cout << "4 not found";

std::lower_bound always returns an iterator - no way around that. std :: lower_bound 总是返回一个迭代器 - 没办法。

Specifically, it returns "Iterator pointing to the first element that is not less than value, or last if no such element is found". 具体来说,它返回“Iterator指向不小于值的第一个元素,如果没有找到这样的元素则返回最后一个”。 (And testing for "last" to determine "not found" is easy). (并且测试“最后”以确定“未找到”很容易)。

That's the definition of the algorithm. 这就是算法的定义。 If that suits your needs, use it. 如果这符合您的需求,请使用它。 If not, don't use it. 如果没有,请不要使用它。

The reason that std::lower_bound( begin, end, value ) does not return end when element value is not found because it makes it more generic. 当找不到元素value时, std::lower_bound( begin, end, value )不返回end原因是因为它使它更通用。 For example if you want to find sequence in sorted container that contain 3, 4 or 5s can be written as: 例如,如果要在已排序的容器中查找包含3,4或5的序列,可以写为:

auto b = std::lower_bound( begin, end, 3 );
auto e = std::upper_bound( b, end, 5 );

after this range [b,e) will have elements 3,4,5s if any or empty range in which case b == e . 在此范围之后[b,e)将具有元素3,4,5s(如果有)或空范围,在这种情况下b == e In this case if there are no elements with value 3 in container (but 4 or 5) and it would work you want it will not find them. 在这种情况下,如果容器中没有值为3的元素(但是4或5)并且它可以工作,那么您将无法找到它们。 On another side adapting lower_bound() for your case (put additional check or use std::equal_range() and compare both iterators) is trivial. 另一方面,为你的情况调整lower_bound() (添加额外的检查或使用std::equal_range()并比较两个迭代器)是微不足道的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM