繁体   English   中英

使用 for_each 调用成员函数

[英]Call a member function using for_each

这是我的原始代码

#include "stdafx.h"
#include <string>
#include <list>
#include <algorithm>
using namespace std;


class testing
{
public:
    int value;
    testing(int v)
    {
        value = v;
    }

    int getval()
    {
        return(value);
    }

};

void func(testing& ob)
{
    printf("The value is %d\n", ob.value);
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::list<testing> testvar[3];

    testing t1(0);
    testing t2(1);
    testing t3(3);

    testvar[0].push_back(t1);
    testvar[0].push_back(t2);
    testvar[0].push_back(t3);

    std::for_each(testvar[0].begin(), testvar[0].end(), func);

    printf("Reached End");
    getchar();
    return 0;
}

我修改它使 func 成为成员函数并得到奇怪的编译错误,我在网上搜索,有人告诉使用 bind1st, bind2nd

#include "stdafx.h"
#include <string>
#include <list>
#include <algorithm>
using namespace std;

class testing
{
public:
int value;
testing(int v)
{
    value = v;
}

int getval()
{
    return(value);
}

};

class testing2
{
public:
    std::list<testing> testvar[3];

    void func(testing& ob)
    {
        printf("The value is %d\n", ob.value);
    }

    void driver()
    {
        std::for_each(testvar[0].begin(), testvar[0].end(), func);
    }

};



int _tmain(int argc, _TCHAR* argv[])
{
    testing2 testob;

    testob.driver();


    printf("Reached End");
    getchar();
    return 0;
}

所以我把驱动功能修改成这个

    void driver()
    {
std::for_each(testvar[0].begin(), testvar[0].end(),     std::bind1st(std::mem_fun(&testing2::func), this));
    }

我仍然遇到一些奇怪的编译错误,有人可以解释为什么我们需要以如此奇怪的方式调用成员函数..? bind1st 如何帮助..?

使用 std::bind

 std::for_each(testvar[0].begin(), testvar[0].end(), std::bind(&testing2::func, this, std::placeholders::_1));

或者使用 std::bind/lambdas

 std::for_each(testvar[0].begin(), testvar[0].end(), [this](testing& ob) { func(ob); });

完整:

#include <string>
#include <list>
#include <algorithm>
using namespace std;

struct testing {
    int value;
    testing(int v) { value = v; }
    int getval() { return(value); }
};

struct testing2 {
    std::list<testing> testvar[3];

    void func(testing& ob) {
        printf("The value is %d\n", ob.value);
    }

    void driver() {
        auto f = std::bind(&testing2::func, this, std::placeholders::_1);
        std::for_each(testvar[0].begin(), testvar[0].end(), f);
        std::for_each(testvar[0].begin(), testvar[0].end(), [this](testing& ob) { func(ob); });
    }
};

int main() {
    testing2 testob;
    testob.driver();
    printf("Reached End");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM