Click to See Complete Forum and Search --> : std::for_each question.


Luc Bergeron
October 31st, 2002, 12:16 PM
Hello to all,

Here we go :

Suppose I have a function that takes an int as the only parameter and returns nothing. Let's call it Func1(int).

Suppose, next, that I have a std::vector<int> named coll.

Is there any way to call Func1 for each element in the vector ???

Here's what I tried :

std::for_each(coll.begin(), coll.end(), std::mem_fun(&Func1));

This doesn't work. I've looked at the bind2st algo in the std but i'm not sure how it works. Can someone help me on this please.

Thanks in advance for any help.

Luc.

Philip Nicoletti
October 31st, 2002, 12:40 PM
Should this work ?


std::for_each(coll.begin(), coll.end(),Func1);


Usually mem_fun is used if you are sorting a
vector of objects, and you want to call a
member function of that object.

Luc Bergeron
October 31st, 2002, 12:46 PM
Might I add that Func1 is a method of a class.

Like this :

ActualRealPos::Func1(int)
{
//does something.
}

ActualRealPos::Init()
{
std::vector<int> coll;

std::for_each(coll.begin(), coll.end(), std::mem_fun(&ActualRealPos::Func1));
}

kuphryn
October 31st, 2002, 01:15 PM
Do you want to modify each element as it is passed into Func1()? for_each() is non-mutatable. One solution is transform().

Kuphryn

Luc Bergeron
October 31st, 2002, 01:24 PM
Nope, I only want to call Func1 for each value that are in the vector.

Thanks,

Luc.

kuphryn
October 31st, 2002, 02:29 PM
Here is an example of an function object adaptor.


template <typename T>
class FunctionObjectAdaptor : public std::unary_function<T, void>
{
public:
void operator()(const T lp) const
{
...
}
};


Kuphryn