STL algorithm function missing position info?

Discussion in 'C++' started by thomas, Mar 10, 2008.

  1. thomas

    thomas Guest

    ---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?
    thomas, Mar 10, 2008
    #1
    1. Advertising

  2. thomas

    ppi Guest

    > 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
    ppi, Mar 10, 2008
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ahmed Moustafa
    Replies:
    0
    Views:
    763
    Ahmed Moustafa
    Nov 15, 2003
  2. Bapaiah Katepalli
    Replies:
    1
    Views:
    1,481
    Mike Treseler
    Jun 23, 2006
  3. many_years_after
    Replies:
    6
    Views:
    739
    Pete Becker
    Jul 19, 2007
  4. many_years_after
    Replies:
    2
    Views:
    328
    James Kanze
    Jul 20, 2007
  5. want.to.be.professer
    Replies:
    9
    Views:
    326
    Jerry Coffin
    Jul 13, 2008
Loading...

Share This Page