how do I get for_each to call the member function? It works fine with a non member. I must be missing something basic here:
#include <iostream>
#include <vector>
#include <algorithm>
#include <conio.h>
using namespace std;
class TestClass
{
public:
auto Func(int);
};
auto TestClass::Func(int n)
{
cout << n << " from member. \n";
}
auto Func(int n)
{
cout << n << " from non member. \n";
}
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(4);
v.push_back(7);
v.push_back(8);
TestClass tc;
for_each(v.begin(),v.end(),tc.Func); // -- doesn't work
for_each(v.begin(),v.end(),Func); // -- works
cout << "Press any...";
getch();
return 0;
}
Last edited on
using lambda:
for_each(v.begin(),v.end(),[&](int n){tc.Func(n);});
using std::bind:
1 2
|
//#include <functional>
for_each(v.begin(),v.end(),std::bind(&TestClass::Func, &tc, std::placeholders::_1));
|
Last edited on
i dont think he is going to understand that. he is a beginner.
Consider using a range-based loop instead of std::for_each
After the advent of C++11, the algorithm std::for_each has essentially become obsolete; it remains because legacy code must still be supported.
Short and sweet: for( int i : v ) tc.func(i) ;