U
utab
Dear all, in a container example, this question is asked in exercises
in Accelerated C++ page 154, 8.8? why dont we use (begin+end)/2 instead
of begin + (end - begin) / 2 is that someting related with the
algortihm
if you take a vector lets say
begin end (one past the last)
| |
1 2 3 4 4 6 7 8 9
(begin+end)/2 returns the iter for the 2nd 4.
if you take a vector lets say
begin end (one past the last)
| |
1 2 3 4 4 6 7 8 9 10
(begin+end)/2 returns the iter for the 6.
So this looks right to me also but could not figure out.
template <class Ran, class X>
bool binary_search(Ran begin, Ran end, const X& x)
{
while (begin < end) {
// find the midpoint of the range
Ran mid = begin + (end - begin) / 2; // why dont we use
(begin+end)/2 instead
// see which part of the range contains `x'; keep looking only
in that part
if (x < *mid)
end = mid;
else if (*mid < x)
begin = mid + 1;
// if we got here, then `*mid == x' so we're done
else return true;
}
return false;
}
in Accelerated C++ page 154, 8.8? why dont we use (begin+end)/2 instead
of begin + (end - begin) / 2 is that someting related with the
algortihm
if you take a vector lets say
begin end (one past the last)
| |
1 2 3 4 4 6 7 8 9
(begin+end)/2 returns the iter for the 2nd 4.
if you take a vector lets say
begin end (one past the last)
| |
1 2 3 4 4 6 7 8 9 10
(begin+end)/2 returns the iter for the 6.
So this looks right to me also but could not figure out.
template <class Ran, class X>
bool binary_search(Ran begin, Ran end, const X& x)
{
while (begin < end) {
// find the midpoint of the range
Ran mid = begin + (end - begin) / 2; // why dont we use
(begin+end)/2 instead
// see which part of the range contains `x'; keep looking only
in that part
if (x < *mid)
end = mid;
else if (*mid < x)
begin = mid + 1;
// if we got here, then `*mid == x' so we're done
else return true;
}
return false;
}