簡體   English   中英

在{8,4,6,2}中搜索4時,是否有任何std :: binary_search的實現將返回true?

[英]Is there any implementation of std::binary_search will return true while search for 4 in {8, 4, 6, 2}?

我在一本教科書中讀到了一個問題,其中1表示可能的輸出。 我在VS和g ++中試過它,都給出了0.教科書是錯的嗎?

int t[] = { 8, 4, 6, 2 };
deque<int> d1(t, t + 4);
cout << binary_search(d1.begin(), d1.end(), 4) << endl;

教科書是對的; 問題是理論問題,即使嘗試多個實現也無法幫助您偽造聲明(您可以做的最多就是找到證明聲明的實現)。

binary_search需要一個排序數組,如果你傳遞一個未排序的數組,你將進入未定義的行為領域,在那里一切都會發生,包括找到你的數字並返回true

例如,碰巧使用數組中的第二個位置作為第一個猜測,或者切換到線性搜索短容器的實現可能很容易做到這一點。 地獄,即使是這樣的事情也是完全符合要求的實施:

template<class ForwardIt, class T>
bool binary_search(ForwardIt first, ForwardIt last, const T& value) {
    // check the first two values just because
    for(int i=0; i<2 && first != last; ++i, ++first) {
        if(!(*first<value) && !(value<*first)) return true;
    } 
    first = std::lower_bound(first, last, value);
    return (!(first == last) && !(value < *first));
}

話雖這么說,更有意思的是,不僅1是可能的輸出,而且5或42也是可能的,盡管IMO不太可能比“Segmentation fault(core dumped)”; 這就是說:未定義的行為實際上是未定義的(並且我已經多次看到libstdc ++ std::sort如果傳遞了一個沒有定義嚴格弱順序的比較運算符,則程序崩潰)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM