Reputation: 734
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
bool comp(const pair<int,int> &a,const pair<int,int> &b)
{
return (a.first < b.first);
}
int main(void)
{
vector<pair<int,int>> data;
data.push_back(make_pair(1,7));
data.push_back(make_pair(5,5));
data.push_back(make_pair(2,7));
data.push_back(make_pair(6,7));
data.push_back(make_pair(9,6));
data.push_back(make_pair(2,4));
data.push_back(make_pair(2,8));
sort(data.begin(),data.end());
int key=9;
if(binary_search(data.begin(),data.end(),key,comp))
{
cout<<"Key found"<<endl;
}
else
{
cout<<"Key is not found"<<endl;
}
}
Upvotes: 0
Views: 4913
Reputation: 179887
It's mostly a matter of names. binary_search
searches for elements, so you need to provide an element.
There's also std::partition_point(begin,end, predicate)
, which assumes a partitioned range. A range is partitioned if there's one point in the range such that all elements before it satisfy the predicate and the elements after it do not. (either sub-range can be empty),
Now, any sorted range is also partitioned if you bind the sorting predicate with any value. E.g. the range 1,5,8
is partioned by value<3
but also by value<0
or value<100
. In your case, you can define a lambda predicate [key](std::pair<int,int> p){ return p.first<key; }
.
Upvotes: 1
Reputation: 923
You could define the comparison within a struct for (pair, int)
and (int, pair)
, so the comparisons within binary search know how to compare a pair with an int:
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
struct comp_pair_int {
bool operator()(const pair<int,int> &a, const int & b)
{
return (a.first < b);
}
bool operator()(const int & a,const pair<int,int> &b)
{
return (a < b.first);
}
};
int main(void)
{
vector<pair<int,int>> data;
data.push_back(make_pair(1,7));
data.push_back(make_pair(5,5));
data.push_back(make_pair(2,7));
data.push_back(make_pair(6,7));
data.push_back(make_pair(9,6));
data.push_back(make_pair(2,4));
data.push_back(make_pair(2,8));
sort(data.begin(),data.end());
int key=9;
if(binary_search(data.begin(),data.end(), key,comp_pair_int()))
{
cout<<"Key found"<<endl;
}
else
{
cout<<"Key is not found"<<endl;
}
}
Upvotes: 2