vector, get index from iterator

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Christopher

    vector, get index from iterator

    Seems odd, but I was wondering if I am in the middle of iterating
    through a vector, is there a way to calc which index I am currently
    on? something like: it - vec.begin()?

    I don't want to change the loop to iterate through using indexes
    instead of iterators, I just need the index for a little debug output,
    the rest of the code in the loop uses the iterator.

    thanks.
  • Victor Bazarov

    #2
    Re: vector, get index from iterator

    Christopher wrote:
    Seems odd, but I was wondering if I am in the middle of iterating
    through a vector, is there a way to calc which index I am currently
    on? something like: it - vec.begin()?
    Absolutely! Since vector's iterators are of 'random access' kind,
    the binary minus is defined for them to give the distance. For
    all others you can use 'std::distance' .
    I don't want to change the loop to iterate through using indexes
    instead of iterators, I just need the index for a little debug output,
    the rest of the code in the loop uses the iterator.
    No need to justify yourself :-)

    V
    --
    Please remove capital 'A's when replying by e-mail
    I do not respond to top-posted replies, please don't ask


    Comment

    • Andre Kostur

      #3
      Re: vector, get index from iterator

      Christopher <cpisz@austin.r r.comwrote in news:c6f679ff-5c3d-4af2-ac81-
      18f8e3f8767e@f3 g2000hsg.google groups.com:
      Seems odd, but I was wondering if I am in the middle of iterating
      through a vector, is there a way to calc which index I am currently
      on? something like: it - vec.begin()?
      That would work for vector... but a more general method would be:

      std::distance(v ec.begin(), it);

      I don't want to change the loop to iterate through using indexes
      instead of iterators, I just need the index for a little debug output,
      the rest of the code in the loop uses the iterator.
      Or, maintain the index as you are iterating through:

      for (it = vec.begin(), i = 0; it != vec.end(); ++it, ++i) {
      }

      Comment

      Working...