Getting current iteration in a loop

J

jalina

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<int> l;
// ...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 ?


Tnx,
J.
 
?

=?ISO-8859-15?Q?Juli=E1n?= Albo

jalina said:
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<int> l;
// ...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 () );
 
A

Alan Johnson

Julián Albo said:
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 ;
}
 
?

=?ISO-8859-15?Q?Juli=E1n?= Albo

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?

I don't looked at the standard definition, but for example TC++PL has
several examples where the state of a functor used with for_each is
expected to be preserved and available in his returned result. See 18.4 for
example (but check the errata list first).
 

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

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top