Julián Albo wrote:
jalina wrote:
Is there a way to get the current iteration in a for_each loop ?
For example:
void f(int val)
{
// Here how get the current
// index or iterator that get called
// by the for_each loop ?
}
void g()
{
list<intl;
// ...put some value in l
for_each(l.begin(), l.end(), f);
}
I guess f() has no way to know that is being called in a for_each. So
should I stick to a basic loop to do that or is there a trick ?
The trick is to write code that does what you want. A function has no state,
but you can use a functor.
For example:
class f
{
public:
f () : count (0)
{ }
unsigned int count;
void operator () (int val)
{
// Whatever
++count;
}
};
for_each (l.begin (), l.end (), f () );
Is this guaranteed to work? for_each takes its functor by value,
meaning at least one copy is made. Does it guarantee it won't make any
more copies? For example, would the following be a valid
implementation of for_each?
template <class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f)
{
for (; first != last; ++first)
{
Function g(f) ;
g(*first) ;
}
return f ;
}
--
Alan Johnson