On Jul 11, 2:24 pm, Yan <yvinogra...@gmail.com> wrote:
Hi,
I don't seem to be able to use for_each if it should replace a 'for'
loop in a method (constructor in my case) and inside that 'for' loop a
class member variable is being accessed. The presence of this member
variable prevents me from using a static or global method to be passed
as a third parameter to for_each, and mem_fun doesn't seem to work for
me either as I am not going to execute a method of an iterator but
pass an iterator as a parameter. I am not sure that explanation makes
a lot of sense, so below is a sample code. I would like to be able to
replace the 'for' loop inside C class constructor with a for_each.
Please don't pay attention to what is actually happening with these
two vectors of ints, it's just for illustration purposes. Thanks.
[snipped original code using for()]
How about something like this:
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;
class push_back_double
{
public:
push_back_double( vector<int> & ints ) : p_ints( &ints ) {}
void operator() ( const int & i )
{
p_ints->push_back( i*2 );
}
private:
vector<int> *p_ints;
};
class Test
{
public:
Test( vector<int>::iterator first, vector<int>::iterator last )
{
for_each( first, last, push_back_double(ints));
}
void Dump()
{
copy( ints.begin(), ints.end(),
ostream_iterator<int>(cout,"\n"));
}
private:
vector<int> ints;
};
int main()
{
vector<int> test;
test.push_back( 1 );
test.push_back( 2 );
test.push_back( 3 );
Test t( test.begin(), test.end() );
t.Dump();
}
Though I'm pretty sure this could be done cleaner with mem_fun...
I'll try that next.
Cbeers,
Andre