成员函数适配器基本用法.cpp

本文详细介绍了C++ STL中成员函数适配器的基本用法,通过实例解析了如何使用适配器来改变成员函数的行为,帮助读者深入理解STL中的这一重要概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

《C++STL基础及应用》

#include <iostream>
#include<functional>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
/*
函数适配器
一 绑定,用于将二元函数降为一元函数
	bindlst()
	template<class Pred,class T>
	binder1st<pred>
	bindlist(const Pred &pr,const T&x)
	Pred是二元函数
	二元函数对象第一个参数绑定为x
	返回值相当于bindr1st<Pred>
	(pr,Pred::first_argument_type(x))

	bind2nd()
	template<class Pred,class T>
	binder2nd<Pred>
	bind2nd(const Pred& pr,const T &y)
	Pred是二元函数
	二元函数对象第二个参数绑定为y
	返回值相当于bindr2nd<Pred>
	(pr,Pred::second_argument_type(y))
二 取反
	not1
	template<class Pred>
	unary _negate<Pred>not1(const pred &pr)
	Pred是一元函数
	返回值相当于unary_negate<Pred>(pr)

	not2
	template<class Pred>
	unary _negate<Pred>not2(const pred &pr)
	Pred是二元函数
	返回值相当于binary_negate<Pred>(pr)
三 成员函数适配器
	men_fun
	template<class R,class T>
	mem_fun_t<R,T>men_fun(R (T::*pm)())
	调用类T中的成员函数

	mem_fun_ref
	templat<class R,class T>
	mem_fun_ref_t<R,T>mem_fun_ref(R(T:: *PM)()) ;
	调用类T中的成员函数
四普通函数适配器
	ptr_fun

	把全局函数进一步封装成一元函数
    template<class Arg,class Result>
	pointer_to_unary_function<Arg,Result>
	ptr_fun(Result (*pf)(Arg));

    把全局函数进一步封装成二元函数
    template<class Arg1,class Arg2,class Result>
	pointer_to_binary_funtion<Arg1,Arg2,Result>
	ptr_fun(Result(*pf)(Arg1,Arg2));
*/
//成员函数适配器基本用法
class Student{
    string strno;
    string strname;
public:
    //不一样的类初始化
    Student(string strno,string strname):strno(strno),strname(strname){}
    bool show()
    {
        cout<<strno<<":"<<strname<<endl;
        return true;
    }
};
int main()
{
    	//******mem_fun_ref 直接使用类的对象
    Student s1("1001","zhangsan");
    Student s2("1002","lisi");
    vector<Student> v;
    v.push_back(s1);
    v.push_back(s2);
    /*mem_fun_ref
	templat<class R,class T>
	mem_fun_ref_t<R,T>
	mem_fun_ref(R(T:: *PM)()) ;
	调用类T中的成员函数*/
    //引用,直接使用参数,对参数地址上的值直接进行修改和使用
    for_each(v.begin(),v.end(),mem_fun_ref(&Student::show));
    Student *ps1=new Student("1001","zhangsan");
    Student *ps2=new Student("1002","lisi");


    vector<Student *> pv;
    pv.push_back(ps1);
    pv.push_back(ps2);
    //*******mem_fun_ref使用类的对象的指针
    for_each(pv.begin(),pv.end(),mem_fun(&Student::show));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值