博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
《C++标准程序库》 第5章 Standard Template Library
阅读量:6858 次
发布时间:2019-06-26

本文共 2322 字,大约阅读时间需要 7 分钟。

为了调用算法,必须含入头文件 <algorithm>

#include 
#include
#include
using namespace std;int main(){ vector
vect = {
1,2,3,4}; // -std=c++0x std::cout<<*max_element(vect.begin(),vect.end())<

 

使用 Lambda 表达式的例子:

#include 
#include
#include
struct User{ int id;};int main(){ std::vector
vect = {
{
2},{
1},{
3}}; //以一元判断式作为算法的参数 std::vector
::iterator it = find_if(vect.begin(),vect.end(),[&](User user) { return user.id == 3; }); std::cout<<"it->id:"<
id<

 

函数对象(仿函数)与std::bind1st() 、 std::bind2nd()

#include 
#include
#include
void print(int i,int j){ std::cout<
<<"---"<
<
struct Print : public std::binary_function
{ void operator()(int i) const { std::cout<
<
vect = { 1,2,3}; std::replace_if(vect.begin(),vect.end(),std::bind2nd(std::less
(),2),0); std::for_each(vect.begin(),vect.end(),Print()); std::for_each(vect.begin(),vect.end(),std::bind1st(Print(),3)); std::for_each(vect.begin(),vect.end(),std::bind2nd(Print(),3));}

stl提供的less,greater 等内置仿函数可以直接使用 std::bind1st()、std::bind2nd() 函数绑定,如果要绑定自己定义的二元仿函数,那么就必须从binary_function派生出来。std::binary_function(T,T,void);  第三个参数表示 operator() 的返回值类型。以下附上 less<T>() 仿函数的源码:

template
struct less : public binary_function<_Tp, _Tp, bool> { bool operator()(const _Tp& __x, const _Tp& __y) const { return __x < __y; } };

 

std::mem_fun_ref() 与 std::mem_fun() 的作用就是将一个"成员函数指针"包装成一个仿函数。mem_fun_ref的作用和用法跟mem_fun一样,唯一的不同就是:当容器中存放的是对象实体的时候用mem_fun_ref,当容器中存放的是对象的指针的时候用mem_fun。

#include 
#include
#include
struct User{ User(int _id):id(_id){} int id; void print(int i) { std::cout<<"i:"<
<
user_vect = {
{
1},{
2},{
3}}; User *puser1 = new User(1); User *puser2 = new User(2); std::vector
puser_vect = {puser1,puser2}; std::for_each(user_vect.begin(),user_vect.end(),std::bind2nd(std::mem_fun_ref(&User::print),3)); std::for_each(puser_vect.begin(),puser_vect.end(),std::bind2nd(std::mem_fun(&User::print),3));}

 

 

 

转载地址:http://ftjyl.baihongyu.com/

你可能感兴趣的文章
Transformer 在RxJava中的使用
查看>>
设计模式(8)-命令模式详解(易懂)
查看>>
JavaScript实现自定义的生命周期
查看>>
重读 JVM
查看>>
Dubbo开源现状与未来规划
查看>>
内存泄露
查看>>
MaterialDesign系列文章(八)TabLayout的使用
查看>>
JDK8和JDK9双版本共存
查看>>
搭建大型源码阅读环境——使用 OpenGrok
查看>>
[译] 微服务从设计到部署(五)事件驱动数据管理
查看>>
美团实习| 周记(四)
查看>>
ubuntu切换源
查看>>
编程语言 IDE 对比
查看>>
str与json.dumps的区别
查看>>
swift送礼物动画
查看>>
Python gevent 是如何 patch 标准库的 ?
查看>>
SpringBoot消费BmobAPI
查看>>
一些Java反编译工具/源代码查看工具的介绍
查看>>
vue实践02之vue-router
查看>>
[ JavaScript ] 数据结构与算法 —— 链表
查看>>