How does it prints the value 3?

int main()
{

  int arr[5] = { 4, 5, 1, 0, 1 };
  sort( arr, arr+5 );
  cout<< lower_bound( arr, arr+5, 3 ) - arr <<endl;
  return 0;

}

3 is not present inside the array and it’s and according to the code it helps to find the first occurrence of 3 but 3 is not present so according to me it should print 0, but it is printing 3.Can’t understand the logic please help.

Hi @knownowworld ,
ur doubt can be understood with the following test case.
given arr[]={4,5,1,0,1};
after sorting, arr[]={0,1,1,4,5};
so when u use lower_bound(arr,arr+n,3), the lower_bound function gives the index of next greater element after 3, which is 4 in dis case. So, it gives index of 4 i.e 3.
if u had used lower_bound(arr,arr+n,6), the function would have search for 6 or 6’s next greater element present in array. Since no element is greater than 6, it will give 5 as output which is the index of element after the array end since there is no element in arr greater than or equal to 6.

Hope dis resolves ur doubt.