binary_search in c++ unexpected behaviour

前端 未结 4 822
暖寄归人
暖寄归人 2021-01-25 13:41

The following snippet is returning me 0. I expected it to be 1. What\'s wrong going on here?

#include 
#include 
#include 

        
4条回答
  •  情歌与酒
    2021-01-25 14:15

    "Unexpected behavior"? There's nothing unexpected here.

    The whole idea of binary search algorithm is taking advantage of the fact that the input array is sorted. If the array is not sorted, there can't be any binary search on it.

    When you use std::binary_search (as well as all other standard binary search-based algorithms), the input sequence must be sorted in accordance with the same comparison predicate as the one used by std::binary_search. Since you did not pass any custom predicate to std::binary_search, it will use the ordering defined by < operator. That means that your input Sequence of integers must be sorted in ascending order.

    In your case the input sequence does not satisfy that requirement. std::binary_search cannot be used on it.

提交回复
热议问题