简体   繁体   中英

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 . 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. To see if 4 is in the array you would just use

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.

Specifically, it returns "Iterator pointing to the first element that is not less than value, or last if no such element is found". (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. For example if you want to find sequence in sorted container that contain 3, 4 or 5s can be written as:

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 . 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. On another side adapting lower_bound() for your case (put additional check or use std::equal_range() and compare both iterators) is trivial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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