c++c++11stl-algorithm

Why does std::binary_search return bool?


According to draft N4431, the function std::binary_search in the algorithms library returns a bool, [binary.search]:

  template<class ForwardIterator, class T>
  bool binary_search(ForwardIterator first, ForwardIterator last,
                     const T& value);

  template<class ForwardIterator, class T, class Compare>
  bool binary_search(ForwardIterator first, ForwardIterator last,
                     const T& value, Compare comp);

Requires: The elements e of [first,last) are partitioned with respect to the expressions e < value and !(value < e) or comp(e, value) and !comp(value, e). Also, for all elements e of [first,last), e < value implies !(value < e) or comp(e, value) implies !comp(value, e).

Returns: true if there is an iterator i in the range [first,last) that satisfies the corresponding conditions: !(*i < value) && !(value < *i) or comp(*i, value) == false && comp(value, *i) == false.

Complexity: At most log2(last - first) + O(1) comparisons.

Does anyone know why this is the case?

Most other generic algorithms either return an iterator to the element or an iterator that is equivalent to the iterator denoting the end of the sequence of elements (i.e., one after the last element to be considered in the sequence), which is what I would have expected.


Solution

  • The name of this function in 1994 version of STL was isMember. I think you'd agree that a function with that name should return bool

    http://www.stepanovpapers.com/Stepanov-The_Standard_Template_Library-1994.pdf