簡體   English   中英

使用 std::binary_search 和 std::vector 的問題

[英]Problem using std::binary_search and std::vector

當我嘗試這個

#include <bits/stdc++.h>
using namespace std;
vector <short> g;
int main(){
    g.push_back(3);
    g.push_back(2);
    cout<<binary_search(g.begin(), g.end(), 2);
}

output 為0

但是, cplusplus.comstd::binary_search將返回:

true找到與 val 等效的元素,則返回 true,否則返回false

我認為它必須是1 (或true )而不是0 為什么不呢?

對不起,我英語不好。

問題是您的向量在應用二進制搜索之前沒有排序。

應用std::sort(start_iterator, end_iterator); 在調用 binary_search function 之前;

PS binary_search的算法返回truefalse

之前關於排序的評論是正確的。 這是打印true的程序的更正版本:

#include <bits/stdc++.h>
#include <iomanip>
using namespace std;
vector <short> g;
int main(){
    g.push_back(2);
    g.push_back(3);
    cout<< boolalpha << binary_search(g.begin(), g.end(), 2);
}

暫無
暫無

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

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