您的位置:首页 > 其它

【STL】函数 for_each; bind1st和bind2nd,not1; mem_fun和mem_fun_ref;

2015-05-13 09:43 260 查看
<pre name="code" class="html">



// bind1st和bind2nd函数把一个二元函数对象绑定成为一个一元函数对象。

// 但是由于二元函数对象接受两个参数,在绑定成为一元函数对象时需要将原来两个参数中的一个绑定下来。

//bind1st是绑定第一个参数,bind2nd则是绑定第二个参数。

如果要对容器vECS中的所有对象都进行相同的操作而不自己写循环的话。

for_each(vECS.begin(),vECS.end(), mem_fun(&ClxECS::DoSomething));

mem_fun_ref的作用和用法跟mem_fun一样,唯一的不同就是:
当容器中存放的是对象实体的时候用mem_fun_ref,
当容器中存放的是对象指针的时候用mem_fun。

bind1st和bind2nd的用法。

包含头文件

#include<vector>

#include<algorithm>

#include<functional>

inta[] = {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则表达的意思就恰恰相反

// bind1st方式移除所有大于100的元素

arr.erase(std::remove_if( arr.begin(), arr.end(), std::bind1st(std::less< int>(), 100)), arr.end());

这里的表达式相当于100 <arr.value;

// 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是等价的,那么我们看看下面的表达式:

arr.erase(std::remove_if( arr.begin(), arr.end(), std::not1(std::bind2nd( std::greater< int>(), 100))), arr.end());

说明:not1是否定返回值是单目的函数,std中还有not2它是否定返回值是双目的函数

//http://blog.csdn.net/lalor/article/details/7975621
bind1st和bind2nd的区别

//http://www.cppblog.com/wc250en007/archive/2011/04/18/144455.html

for_each的用法
//http://blog.csdn.net/starlee/article/details/1400811
mem_fun和mem_fun_ref的用法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: