How come it prints 6

In lower_bound it went to set.end(). Which is any garbage value. Because we don’t know what stores there.

Hello @sumitsinghdeode,

It does not perform any computation for the element at set.end().

Foloowing is the implementation of it:
template <class ForwardIterator, class T>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val)
{
ForwardIterator it;
iterator_traits::difference_type count, step;
count = distance(first,last);
while (count>0)
{
it = first;
step=count/2;
advance (it,step);
if (*it<val) {
first=++it;
count-=step+1;
}
else count=step;
}
return first;
}

Can you share the problem?

#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
int main()
{
    set<int>s;
    s.insert(1);
    s.insert(5);
    s.insert(7);
    s.insert(2);
    s.insert(12);
    s.insert(10);
    auto it = s.lower_bound(15);
    cout<< *it <<endl;
    return 0;
}

Hello @sumitsinghdeode,

Return Value: The function returns an iterator pointing to the element in the container which is equivalent to k passed in the parameter. In case k is not present in the set container, the function returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum value in the container, then the iterator returned is equivalent to s.end() (A special iterator points beyond the last element).

And s.end() will return the number of elements int the set:

  1. https://ide.codingblocks.com/s/184917
  2. https://ide.codingblocks.com/s/184918

This is the reason it is returning 6.

Hope, this would help.
Give a like if you are satisfied.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.