So this is the code the book (C++ Primer 5th Edition) gives you
1 2 3 4 5 6 7 8 9 10 11 12 13
// text must be sorted
// beg and end will denote the range we`re searching
auto beg = text.begin(), end = text.end();
auto mid = text.begin() + (end - beg) /2; // original midpoint
// while there are still elements to look at and we haven`t yet found sought
while (mid != end && *mid != sought) {
if (sought < *mid) // is the element we want in the first half?
end = mid; // if so, adjust the range to ignore the second half
}else {
beg = mid + 1;
}
mid = beg + (end - beg)/2; // new midpoint <- this
}
In the binary search program on page 112, why did we write mid = beg + (end - beg) / 2; instead of mid = (beg + end) /2;?
No, it's impossible to do. The program doesn't compile if you do that. Think about it. What would the sum of two iterators be? If you find iterators hard to grasp think of them as pointers. It's not possible to add two pointers for the same reason.