先不要被吓到,其实这两个配接器很简单。
首先,他们都在头文件中定义。
其次,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));
cout << res << endl;
//查找元素值小于10的元素的个数
//也就是使得elem < 10成立的元素个数
res = count_if(coll.begin(), coll.end(), bind2nd(less<int>(), 10));
cout << res << endl;
return 0;
}
程序的输出结果是0 9
原文链接:
http://www.programlife.net/stl-bind1st-bind2nd-demo.html