这是我的原始代码
#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");
}
关于c++ - 使用 for_each 调用成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18006685/