[英]c++ stl using compare predicate/functor with containers
I haven't touched C++ in a few years so please bear with me. 几年来我没有接触过C ++,所以请多多包涵。 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 比较器中存在相同的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.