lower bound

I am doing hackerrank questions and one requires the use of lower_bound, so i read it on the cpp.reference, and it says
"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, or last if no such element is found."
From this i take it to mean, if the element is found, then the iterator will point to an element that is equal to or more than what is being searched for.
Or it will point to the last element in the container if the element being looked for is not found. However, when i put this code to use (example code below), it seems like I am not getting an iterator to the last element in the container, and seems to be returning an iterator to where the element being searched for would be placed.
Am I just misunderstanding what the cpp reference doc is saying, or am I doing something else wrong?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
  int main()
{
    // Input vector
    std::vector<int> v{ 10, 20, 30, 30, 30, 40, 50 };
 
    // Print vector
    std::cout << "Vector contains :";
    for (unsigned int i = 0; i < v.size(); i++)
        std::cout << " " << v[i];
    std::cout << "\n";
 
    std::vector<int>::iterator low1, low2, low3;
     
    // std :: lower_bound
    low1 = std::lower_bound(v.begin(), v.end(), 30);
    low2 = std::lower_bound(v.begin(), v.end(), 35);
    low3 = std::lower_bound(v.begin(), v.end(), 55);
 
    // Printing the lower bounds
    std::cout
        << "\nlower_bound for element 30 at position : "
        << (low1 - v.begin());
    std::cout
        << "\nlower_bound for element 35 at position : "
        << (low2 - v.begin());
    std::cout
        << "\nlower_bound for element 55 at position : "
        << (low3 - v.begin());
 
    return 0;
}
Last edited on
Sounds like you're misunderstanding the reference page. All the algorithm does is find the first element of a range that's not less than some value. So for example
std::lower_bound(v.begin(), v.end(), 35);
Gives you an iterator to the first element in v that is not less than 35.

The value 35 doesn't have to exist in the range.
Look at what std::vector::end() means:

It is PAST the last element of the vector.

https://en.cppreference.com/w/cpp/container/vector/end

55 is greater than any of the elements in your vector. std::vector::end() would indicate search failed, value not found.
Topic archived. No new replies allowed.