position in a vector

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • avimitrani
    New Member
    • Sep 2006
    • 7

    position in a vector

    Hi,

    I have an iterator that points to an item in a vector. How do I get the item's position in the vector (its distance from vec.begin() )?

    Thanks,
    Avi.
  • D_C
    Contributor
    • Jun 2006
    • 293

    #2
    Does this help Avi?
    Code:
      vector<unsigned int>::iterator it;
      for(it = vec.begin(); it != vec.end(); it++)
        cout << it-vec.begin() << " " << *it << " " << vec.end()-it << endl;

    Comment

    • avimitrani
      New Member
      • Sep 2006
      • 7

      #3
      Looping over the vector may be costly. I'm looking for an 'arithmetic' calculation.

      are the last two lines correct?:

      vector<int> vec
      // Here vec is filled...
      vector<int>::it erator p;
      // Here p is made to point to an element of vec...

      vector <int>::differen ce_type position;
      position = p - vec.begin()

      Thanks,
      Avi.

      Comment

      • vmohanaraj
        New Member
        • Jul 2006
        • 14

        #4
        You can use the distance function provided for this purpose in STL. See the following example.

        #include <iostream>
        #include <vector>


        int main() {
        std::vector<int > v;
        v.push_back(0);
        v.push_back(1);
        v.push_back(2);
        v.push_back(3);

        std::vector<int >::const_iterat or i1, i2;

        i1 = v.begin();

        i2 = i1+2;
        std::cout << distance(i1, i2);
        }

        The output for this would be 2.

        Comment

        • avimitrani
          New Member
          • Sep 2006
          • 7

          #5
          Thank you, vmohanaraj.
          This is what I was looking for.

          Comment

          Working...