---
title: "对STL中绑定器bind1st, bind2nd的理解"
author: "larrytang"
date: "2010-12-23T15:20:22Z"
tags: ["F#", "算法"]
categories: ["编程语言"]
slug: "stl-bind1st-bind2nd"
draft: false
lastmod: "2010-12-23T15:23:17Z"
id: 850260
url: "https://larrytang.iteye.com/blog/850260"
---

一个绑定器使用另一个函数对象f()和参数值V创建一个函数对象。被绑定函数对象必须为双目函数，也就是说有两个参数,A和B。STL 中的帮定器有：  
·bind1st() 创建一个函数对象，该函数对象将值V作为第一个参数A。  
·bind2nd()创建一个函数对象，该函数对象将值V作为第二个参数B。

```
#include <stdafx.h>
#include <iostream>
#include <algorithm>
#include <functional>
#include <list>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	int iarray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
	list<int> aList(iarray, iarray + 10);

	int k = 0;
	k = count_if(aList.begin(), aList.end(), bind1st(greater<int>(), 8));
	cout << "Number elements < 8 == " << k << endl;

	return 0;
}
```

count\_if()计算满足特定条件的元素的数目。 这是通过将一个函数对象和一个参数捆绑到为一个对象，并将该对象作为算法的第三个参数实现的。 注意这个表达式:

```
bind1st(greater<int>(), 8)
```

该表达式将greater&lt;int&gt;()和一个参数值8捆绑为一个函数对象。由于使用了bind1st()，所以该函数相当于计算下述表达式：

```
8 > q
```

表达式中的q是容器中的对象。因此这条语句是计算所有小于或等于8的对象的数目，所以结果是7。

如果将bind1st(greater&lt;int&gt;(), 8)改成

```
bind2nd(greater<int>(), 8)
```

则表示：q &gt; 8 , 此时结果就是2了。