I haven't touched C++ in a few years so please bear with me. I need to do binary search in a sorted vector of other containers, let's say pairs, but whatever the reason I cannot get a few lines to compile.
So, for starters, this compiles fine:
bool cmp_pair( int l, int r )
{
return l < r;
}
main ()
{
vector<int> v;
binary_search( v.begin(), v.end(), 0, cmp_pair );
return 0;
}
But this doesn't:
bool cmp_pair( const pair<int,int>& l, const pair<int,int>& r )
{
return l.first < r.first;
}
main ()
{
vector< pair< int, int > > v;
binary_search( v.begin(), v.end(), 0, cmp_pair );
return 0;
}
Functor doesn't help either:
struct cmp_pair {
bool operator()( const pair<int,int>& l, const pair<int,int>& r )
{
return l.first < r.first;
}
};
main ()
{
vector< pair< int, int > > v;
binary_search( v.begin(), v.end(), 0, cmp_pair() );
return 0;
}
Since you are doing binary search on vector of pairs so third argument should be pair so your code should be like this :
using namespace std;
bool cmp_pair( const pair<int,int>& l, const pair<int,int>& r )
{
return l.first < r.first;
}
int main ()
{
vector< pair< int, int > > v;
if(binary_search( v.begin(), v.end(), std::make_pair(0,0), cmp_pair ))
{
std::cout<<"found...."<<std::endl;
}
else
{
std::cout<<"not found...."<<std::endl;
}
return 0;
}
Same problem exists in your comparator
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.