Dave's Brain

Browse - programming tips - convert vector iterator to an index

Date: 2008apr18
Language: C++

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, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.