algorithm - c++ primer Binary Search by iterator -


the question in comment!

code:

auto beg = text.begin(), end = text.end();   auto mid = text.begin() + (end - beg) / 2;  while(mid != end && *mid != key)    {      if (key < *mid)         end = mid;   //why not end = mid - 1??     else         beg = mid + 1;     mid = beg + (end - beg) / 2; } 

this question have stuck me long time.

a shorter answer:

the invariant end "one past end" of interval search.

since interval want search beg .. mid-1, mid "one past end" iterator.


Comments