Dave's Brain

Browse - Programming Tips - How do I convert a STL vector iterator into an integer index?

Date: 2008apr18
Language: C++
Keywords: stl, std

Q.  How do I convert a STL vector iterator into an integer index?

A.  Do this:

#include <vector> typedef std::vector<char *> MYARRAY; // This does the trick inline const int iterator_to_index(MYARRAY &a, MYARRAY::iterator it) { return it - a.begin(); } // Example use main() { MYARRAY a; int index; a.push_back("one"); a.push_back("two"); a.push_back("three"); for (MYARRAY::iterator it = a.begin(); it != a.end(); it++) { index = iterator_to_index(a, it); printf("index=%d\n", index); } }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.