使用std::bind的时候,使用_2编译出错。_1就没有问题。为什么?
我有下面的代码,查找一个数组里面比8大的数的个数和比8小的数的个数:
#include<algorithm>
#include<functional>
#include<iostream>
using namespace std;
using namespace placeholders;
int main()
{
int buf[]={4,2,6,7,15};
cout<<count_if(begin(buf),end(buf),bind(less<int>(),8,_1))<<endl;//找比8大的数的数量,ok,打印1
cout<<count_if(begin(buf),end(buf),bind(less<int>(),8,_2))<<endl;//编译错误
return 0;
}
1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\algorithm(109): error C2451: conditional expression of type 'std::_Do_call_ret<_Forced,_Ret,_Funx,_Btuple,_Ftuple>::type' is illegal
1> with
1> [
1> _Forced=false,
1> _Ret=void,
1> _Funx=std::less<int>,
1> _Btuple=std::tuple<int,std::_Ph<2>>,
1> _Ftuple=std::tuple<int &,std::_Nil,std::_Nil,std::_Nil,std::_Nil,std::_Nil,std::_Nil,std::_Nil>
1> ]
1> Expressions of type void cannot be converted to other types
1> c:\program files (x86)\microsoft visual studio 11.0\vc\include\algorithm(121) : see reference to function template instantiation 'std::iterator_traits<_Iter>::difference_type std::_Count_if<_Iter,_Pr>(_InIt,_InIt,_Pr)' being compiled
1> with
1> [
1> _Iter=int *,
1> _Pr=std::_Bind<false,void,std::less<int>,int,std::_Ph<2> &,std::_Nil,std::_Nil,std::_Nil,std::_Nil,std::_Nil>,
1> _InIt=int *
1> ]
1> d:\documents\visual studio 2012\projects\consoleapplication1\consoleapplication2\consoleapplication2.cpp(19) : see reference to function template instantiation 'std::iterator_traits<_Iter>::difference_type std::count_if<_Ty*,std::_Bind<_Forced,_Ret,_Fun,_V0_t,_V1_t,_V2_t,_V3_t,_V4_t,_V5_t,<unnamed-symbol>>>(_InIt,_InIt,_Pr)' being compiled
1> with
1> [
1> _Iter=int *,
1> _Ty=int,
1> _Forced=false,
1> _Ret=void,
1> _Fun=std::less<int>,
1> _V0_t=int,
1> _V1_t=std::_Ph<2> &,
1> _V2_t=std::_Nil,
1> _V3_t=std::_Nil,
1> _V4_t=std::_Nil,
1> _V5_t=std::_Nil,
1> <unnamed-symbol>=std::_Nil,
1> _InIt=int *,
1> _Pr=std::_Bind<false,void,std::less<int>,int,std::_Ph<2> &,std::_Nil,std::_Nil,std::_Nil,std::_Nil,std::_Nil>
1> ]
[解决办法]
因为楼主没有认真看bind的文档,根本不知道_1/_2是干嘛的。
count_if只接受一个参数的functor,哪来_2呢。多认真看例子吧。