bind1st和bind2nd这两个函数的用法。
2009-09-17 15:12
176 查看
bind1st和bind2nd函数用于将一个二元算子(binary functor,bf)转换成一元算子(unary functor,uf)。为了达到这个目的,它们需要两个参数:要转换的bf和一个值(v)。
可能这么解释以后大家还不是很清楚,那么就说点白话吧。我们在做比较的时候所写的表达式像 x > k ,x < k,这里的k是一个参数表示你程序里面的表达式要和k值去比较。上面这两个表达式对应的应该是bind2nd ,简单的理解就是把k作为比较表达式的第二个参数。如果使用bind1st则对应的表达式是 k > x,k < x,也就是把k作为比较表达式的第一个参数。大家可能会注意到这里面没有=的比较,先别着急,后面将会说道如何实现=的比较。先举两个例子看看bind1st和bind2nd的用法。
int a[] = {1, 2, 100, 200};
std::vector< int> arr(a, a + 4);
// 移除所有小于100的元素
arr.erase( std::remove_if( arr.begin(), arr.end(),
std::bind2nd( std::less< int>(), 100)), arr.end());
这里的比较表达式相当于arr.value < 100
如果用bind1st则表达的意思就恰恰相反
// 移除所有大于100的元素
arr.erase( std::remove_if( arr.begin(), arr.end(),
std::bind1st( std::less< int>(), 100)), arr.end());
这里的表达式相当于100 < arr.value
当然为了实现删除大于100的元素你同样可以使用bind2nd
// 移除所有大于100的元素
arr.erase( std::remove_if( arr.begin(), arr.end(),
std::bind2nd( std::greater< int>(), 100)), arr.end());
前面说道=的比较,比如说x <= k怎么实现呢,std又提供了一个好东西not1,我们可以说 !(x > k) 和 x <= k是等价的,那么我们看看下面的表达式:
// 移除所有小于等于100的元素
arr.erase( std::remove_if( arr.begin(), arr.end(),
std::not1(std::bind2nd( std::greater< int>(), 100))), arr.end());
说明:not1是否定返回值是单目的函数,std中还有not2它是否定返回值是双目的函数
例子需要包含头文件
#include <vector>
#include <algorithm>
#include <functional>
int a[] = {1, 2, 100, 200};
std::vector< int> arr(a, a + 4);
// 移除所有小于100的元素
arr.erase( std::remove_if( arr.begin(), arr.end(),
std::bind2nd( std::less< int>(), 100)), arr.end());
这里的比较表达式相当于arr.value < 100
如果用bind1st则表达的意思就恰恰相反
// 移除所有大于100的元素
arr.erase( std::remove_if( arr.begin(), arr.end(),
std::bind1st( std::less< int>(), 100)), arr.end());
这里的表达式相当于100 < arr.value
当然为了实现删除大于100的元素你同样可以使用bind2nd
// 移除所有大于100的元素
arr.erase( std::remove_if( arr.begin(), arr.end(),
std::bind2nd( std::greater< int>(), 100)), arr.end());
前面说道=的比较,比如说x <= k怎么实现呢,std又提供了一个好东西not1,我们可以说 !(x > k) 和 x <= k是等价的,那么我们看看下面的表达式:
// 移除所有小于等于100的元素
arr.erase( std::remove_if( arr.begin(), arr.end(),
std::not1(std::bind2nd( std::greater< int>(), 100))), arr.end());
说明:not1是否定返回值是单目的函数,std中还有not2它是否定返回值是双目的函数
例子需要包含头文件
#include <vector>
#include <algorithm>
#include <functional>
相关文章推荐
- bind1st和bind2nd这两个函数的用法
- bind1st, bind2nd, mem_fun, mem_fun_ref,这三个函数的使用
- bind1st和bind2nd函数用于将一个二元算子
- Python中.join()和os.path.join()两个函数的用法详解
- mysql中计算两个日期的时间差函数TIMESTAMPDIFF用法
- memcpy和strncpy两个函数用法
- 用来获取子串的两个函数substr和substring用法比较
- 【STL】bind1st与bind2nd函数解析
- Oracle lead 和 lga 两个函数的用途和用法
- toggle的用法(点击更换不同的function)当指定元素被点击时,在两个或多个函数之间轮流切换。
- matlab中zeros 和 ones 这两个函数的用法以及size的用法,princomp,pcacov,pcares,barttest四大分析函数用法
- memcpy和strncpy两个函数用法
- CSpinButtonCtrl::GetPos()和GetPos32( )两个函数的用法
- c# string两个函数的用法
- opengl红宝书关于name stack操作两个函数glLoadName,glPushName的用法区别
- 关于函数适配器less< Type>以及bind1st和bind2nd的使用
- Oracle lead 和 lga 两个函数的用途和用法
- mysql中计算两个日期的时间差函数TIMESTAMPDIFF用法
- 【STL】bind1st与bind2nd函数解析
- 两个很实用很方便的函数核心及用法{(lower_bound)+(max_element))~~