Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   STL algorithm function missing position info? (http://www.velocityreviews.com/forums/t597309-stl-algorithm-function-missing-position-info.html)

 thomas 03-10-2008 02:31 AM

STL algorithm function missing position info?

---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?

 ppi 03-10-2008 02:24 PM

Re: STL algorithm function missing position info?

> 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

 All times are GMT. The time now is 10:17 AM.