std::for_each question

D

Dylan

At the moment I often find myself doing something like the following

std::list<MyClass*> mcl;

/.../fill mcl with some elements

//now call aMethod() for each element;
for (std::list<MyClass*>::iterator it = mcl.begin();
it != mcl.end();
++it)
{
it->aMethod();
}

Is there a *convenient* way of using something like std::for_each to
achieve the same result as the loop shown in the previous code
snippet?

thanks
 
J

jota

Dylan said:
At the moment I often find myself doing something like the following

std::list<MyClass*> mcl;

std::for_each(mcl.begin(),mcl.end(),aMethod);
//jota
 
B

Buster

Dylan said:
At the moment I often find myself doing something like the following

std::list<MyClass*> mcl;

/.../fill mcl with some elements

//now call aMethod() for each element;
for (std::list<MyClass*>::iterator it = mcl.begin();
it != mcl.end();
++it)
{
it->aMethod();
}

Is there a *convenient* way of using something like std::for_each to
achieve the same result as the loop shown in the previous code
snippet?

std::for_each (mcl.begin (), mcl.end (),
std::mem_fun (& MyClass::aMethod));
 
P

Pete Becker

Dylan said:
Is there a *convenient* way of using something like std::for_each to
achieve the same result as the loop shown in the previous code
snippet?

Read about std::mem_fun.
 
P

Pete Becker

jota said:
std::for_each(mcl.begin(),mcl.end(),aMethod);

Not quite. This would attempt to call aMethod(*iter), which is fine if
aMethod is an ordinary function, but what you need with a member
function is (*iter)->aMethod. Use

std::for_each(mc1.begin(), mc1.end(), mem_fun(&MyClass::aMethod));
 
?

=?iso-8859-1?q?Josep_Mon=E9s_i_Teixidor?=

At the moment I often find myself doing something like the following

std::list<MyClass*> mcl;

/.../fill mcl with some elements

//now call aMethod() for each element;
for (std::list<MyClass*>::iterator it = mcl.begin();
it != mcl.end();
++it)
{
it->aMethod();
}

Is there a *convenient* way of using something like std::for_each to
achieve the same result as the loop shown in the previous code
snippet?

I think you could use something like:

std::for_each(mcl.begin(), mcl.end(), std::mem_fun(&MyClass::aMethod))

If you want it to be even more powerful, try Boost. For instance, look at
this sample:
http://www.boost.org/libs/bind/bind.html#with_algorithms

Regards,

Josep
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top