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.
How does it prints the value 3?
Hey due some technical issue, question is not visible to me, if you could provide me the question It would help me in solving your doubt.
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; }
Lower_bound functions returns the iterator/pointer to the first element that is equal or greater than the given element. In your code array after sorting is: 0 1 1 4 5
Now we 4 is the first element that is bigger than 3, so lower_bound will return iterator to that position. You are subtracting the return value with arr, so your final output will become index of 4 which is 3.