std::mem_fun vs std::mem_fn, std::bind1st/std::bind2nd vs std::bind

本文讨论了在C++编程中,如何在不同情况下选择使用std::mem_fun, std::mem_fn, std::bind1st/std::bind2nd以及std::bind。std::mem_fun和std::mem_fn用于调用成员函数,但std::mem_fn支持任意参数数量。std::bind1st和std::bind2nd已被弃用,取而代之的是更灵活的std::bind,它能处理任意参数个数。文章还举例说明了如何使用std::bind来绑定类成员函数并传递参数。" 121243300,9973860,快递转运与时效分析:全国各大区数据解读,"['数据分析', '数据挖掘', '数据建模', '物流网络', '快递服务']

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

1.mem_fun vs mem_fn

在C++ 11之前,当需要使用STL算法对容器中的对象一次调用成员函数时,我们需要使用到mem_fun或者mem_fun_ref,至于mem_fun和mem_fun_ref之间的选择根据容器中存储的对象是对象指针还是对象本身来选择,其中mem_fun针对对象本身,而mem_fun_ref则针对对象本身。例如,

class T
{
public:
    T() = default;
    ~T() = default;
                               
    void doSomething()
    {
        cout << "do something" << endl;
    }
};

vector<T> vecT;
vecT.emplace_back(1);
vecT.emplace_back(2);
std::for_each(vecT.begin(), vecT.end(), mem_fun_ref(&T::print));

vector<T*> vecT;
vecT.emplace_back(new T(1));
vecT.emplace_back(new T(2));
std::for_each(vecT.begin(), vecT.end(), mem_fun(&T::print));

但是在C++ 11之后,mem_fun和mem_fun_ref已经被标记为de
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值