Here is the code. As a result I get "4 4". Don't understand why it is not "2 4" (according to lower and upper bounds' defenitions).
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v = {1, 2, 4, 5};
vector<int>::iterator s , f;
s = lower_bound(v.begin(), v.end(), 3);
f = upper_bound(v.begin(), v.end(), 3);
cout << (*s) << " " << (*f);
return 0;
}
From
std::lower_bound
:The first element (from the beginning of the vector) which is not less than
3
is4
and hencelower_bound
returns4
.From
std::upper_bound
:The first element (from the beginning of the vector) which is greater than
3
is4
and henceupper_bound
returns4
.The reason for this confusion is because
upper_bound
returns the first element that is greater than the given value, so by symmetry we expectlower_bound
to return the last element (from the beginning of the vector) that is less than the given value. But alas, thestd
function doesn't obey this "expected" symmetry.The naming of
lower_bound
andupper_bound
is unfortunate as it invites confusion. The names refer to the results when searching through a sequence that has multiple elements that are exactly equivalent to the one you're searching;lower_bound
returns the iterator to the start, andupper_bound
returns one past the end.When the element isn't part of the sequence, they both return an iterator to the first element greater than the one you were searching for. This might be the
end
iterator if there are none greater.It would be easier to understand/remember what
std::lower_bound()
andstd::upper_bound()
return knowing thatstd::equal_range()
returns a pair of iterators, where the first one is equal to whatstd::lower_bound()
returns, and the second one is equal to whatstd::upper_bound()
returns.So, here are different cases when they are called with a parameter of
4
:Where
E
means whatcontainer.end()
returns - an iterator behind the last element.