先不要被吓到,其实这两个配接器很简单。
首先,他们都在头文件<functional>中定义。
其次,bind就是绑定的意思,而1st就代表first,2nd就代表second,现在名在可以很快记住了。
再次,他们的申明是一样的,都是(const Operation& op, const T& x)。
简单的说,bind1st(const Operation& op, const T& x)就是这么一个操作:x op value,而bind2nd(const Operation& op, const T& x)就是这么一个操作:value op x,其中value是被应用bind的对象。这两个配接器都用于将一个二元算子转换成一个一元算子。下面来看一段代码吧!
//Coded by www.programlife.net
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> coll;
for(int i = 1; i <= 10; ++i)
{
coll.push_back(i);
}
//查找元素值大于10的元素的个数
//也就是使得10 < elem成立的元素个数
int res = count_if(coll.begin(), coll.end(), bind1st(less<int>(), 10));
template<class _Ty>
struct less
: public binary_function<_Ty, _Ty, bool>
{ // functor for operator<
bool operator()(const _Ty& _Left, const _Ty& _Right) const
{ // apply operator< to operands
return (_Left < _Right);
}
};
less是二元函数对象,bind1st(less<int>(), 10)就是将10赋值给less模板中的left;bind2nd(less<int>(), 10));中的10赋值给了right
所以就有上面的结果;
cout << res << endl; //查找元素值小于10的元素的个数 //也就是使得elem < 10成立的元素个数 res = count_if(coll.begin(), coll.end(), bind2nd(less<int>(), 10)); cout << res << endl; return 0; }
程序的输出结果是0 9
not1 not2就是对bind1nd和bind2ndqufan 取反;但是count_if(coll.begin(), coll.end(), bind2nd(less<int>(), 10)); 和
count_if(coll.begin(), coll.end(), not1(bind1st(less<int>(), 10)));的结果不一定一样
std::vector<int> vec;
vec.push_back(2);
vec.push_back(23);
vec.push_back(42);
vec.push_back(62);
vec.push_back(62);
vec.push_back(72);
vec.push_back(72);
// 大于62
std::cout << count_if(vec.begin(),vec.end(), not1(bind1st(less<int>() , 62))) << std::endl;;
//<62
std::cout << count_if(vec.begin(),vec.end(), bind2nd(less<int>() , 62));
system("pause");
结果是 5 3,
浙公网安备 33010602011771号