binary_search in c++ unexpected behaviour

前端 未结 4 862
暖寄归人
暖寄归人 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:23

    Your array is not sorted, so binary_search got undefined behavior. Try std::find instead

    bool found = std::find(v.begin(), v.end(), 10) != v.end()
    

    §25.4.3.4 of the C++11 standard (3242 draft)

    1. 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).

提交回复
热议问题