简体   繁体   中英

Shouldn't lower_bound return an iterator pointing to end()?

I am trying to understand lower_bound better. 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. 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 .

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() . However, what I get is:

-1 at index 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. In your case that would be the beginning of the sequence.

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