Xing215
Xing215

Reputation: 31

Problem using std::binary_search and std::vector

When I try this

#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);
}

The output is 0.

However, cplusplus.com said that std::binary_search will return:

true if an element equivalent to val is found, and false otherwise.

I think it must be 1 (or true) instead of 0. Why doesn't it?

I'm sorry that I'm not good at English.

Upvotes: 1

Views: 81

Answers (2)

Fedor
Fedor

Reputation: 21251

The previous comments about sorting are right. Here is a corrected version of your program that prints 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);
}

Upvotes: 0

dixit_chandra
dixit_chandra

Reputation: 478

Problem is that your vector is not sorted before applying binary search.

Apply std::sort(start_iterator, end_iterator); before calling binary_search function;

P.S. the algorithm of binary_search returns true or false.

Upvotes: 4

Related Questions