STL bind1st、bind2nd的使用【转】
来源:互联网 发布:比赛顺序抽签软件 编辑:程序博客网 时间:2024/05/04 18:08
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>
- STL bind1st、bind2nd的使用【转】
- (转)bind1st、bind2nd的使用
- STL: bind1st, bind2nd 的使用(C++)
- bind1st bind2nd的使用
- bind1st bind2nd的使用
- bind1st bind2nd的使用
- bind1st bind2nd的使用
- (转)解析bind1st和bind2nd的使用
- (转)解析bind1st和bind2nd的使用
- STL的bind1st,bind2nd,mem_fun,mem_fun_ref使用示例
- STL中bind1st和bind2nd的区别
- stl之bind1st,bind2nd解读(转)
- STL bind1st bind2nd详解
- STL bind1st bind2nd详解
- 解析bind1st和bind2nd的使用
- 解析bind1st和bind2nd的使用
- 解析bind1st和bind2nd的使用
- stl中 bind1st和 bind2nd 以及not1等适配器的使用
- 关于浏览器自动加上<pre>标签
- ORACLE 10G安装文档for RedHat 5.4
- 网站首屏下载时间决定电子商务输赢
- Java日期时间函数
- 软件加密之惑
- STL bind1st、bind2nd的使用【转】
- linux 内存管理图示
- IPStatus 枚举
- 丢失Android系统库或者Conversion to Dalvik format failed with error 1错误的解决
- 业务流程管理工具的概览和比较分析
- ORA-20002: Version of statistics table APPLSYS.FND_STATTAB is too old.
- 构建erlang的app
- mysql学习之--4、mysql浮点型
- Iterator对象的remove方法是迭代过程中删除元素的唯一方法