可可西

bind1st/bind2nd

1. bind1st/bind2nd

bind1st:  绑定器binder通过把二元函数对象的第一个实参绑定到一个特殊的值上将其转换成一元函数对象

bind2nd: 绑定器binder通过把二元函数对象的第二个实参绑定到一个特殊的值上将其转换成一元函数对象

例如:

1 bool kPrint(int i, int j)
2 {
3 std::cout<< i << "---" << j << std::endl;
4 return i>j;
5 }
6
7  int _tmain(int argc, _TCHAR* argv[])
8 {
9 // 以下函数调用等价于调用kPrint(2,1)
10   (std::bind1st(std::ptr_fun(kPrint), 2))(1);
11 // 以下函数调用等价于调用kPrint(1,2)
12 (std::bind2nd(std::ptr_fun(kPrint), 2))(1);
13
14 return 0;
15 }

说明:std::ptr_fun是将函数指针转换为仿函数指针。


其它应用:

计算数组中元素小于等于10的个数

1 void funA()
2 {
3 using namespace std;
4 vector<int> va;
5 va.push_back(5);
6 va.push_back(79);
7 va.push_back(23);
8 va.push_back(6);
9 va.push_back(1);
10 va.push_back(10);
// 设c为va中的一个元素  
// bind2nd(less_equal<int>(), 10) --> less_equal<int>(c, 10)
11 int less10 = count_if( va.begin(), va.end(), bind2nd(less_equal<int>(), 10));
12 cout << less10 << endl;
13 }
14
15  // 以下是less_equal的实现部分
16  template<class _Ty>
17 struct less_equal
18 : public binary_function<_Ty, _Ty, bool>
19 { // functor for operator<=
20   bool operator()(const _Ty& _Left, const _Ty& _Right) const
21 { // apply operator<= to operands
22   return (_Left <= _Right);
23 }
24 };
25  


posted on 2010-10-22 12:04  可可西  阅读(772)  评论(0编辑  收藏  举报

导航