STL algorithm function missing position info?

T

thomas

---code---
int func(int &elem) const{
return elem+2;
}
vector<int> vec(30,0);
foreach(vec.begin(), vec.end(), func);
----code-----

As we see that the "func" function can only do operations on the
"elem" itself, not the iterator.
But if I want to do this:

for each element in vector vec
*elem = iter - vec.begin(); //its position in the vector.

how can I do this? in the "func" function, I only can see the
"elem"(int), I cannot get the "iter"(iterator), so the position info
is missing?

Of course I know that I can do it by a for loop, but any other way to
do it?
 
P

ppi

for each element in vector vec
*elem = iter - vec.begin(); //its position in the vector.

how can I do this? in the "func" function, I only can see the
"elem"(int), I cannot get the "iter"(iterator), so the position info
is missing?

Of course I know that I can do it by a for loop, but any other way to
do it?

Not with a for_each statement. I do not know of any mechanism to get
the iterator from a value passed to a function.
Well, you can try to simulate it with that kind of code:

struct fill_with_pos
{
mutable unsigned int last_pos;

fill_with_pos() : last_pos(0){}
void operator()( int& a ) const { a = last_pos++; }
}

std::for_each(vec.begin(), vec.end(), fill_with_pos() );

slightly better than a loop (filling operation still abstracted
through a function) but not much.
Hope this will help,

Cheers,
-- Paulo
 

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,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top