I frequently find myself requiring to iterate over STL vectors. While I am doing this I require access to both the vector element and its index.
I used to do this as:
typedef std::vector<Foo> FooVec;
typedef FooVec::iterator FooVecIter;
FooVec fooVec;
int index = 0;
for (FooVecIter i = fooVec.begin(); i != fooVec.end(); ++i, ++index)
{
Foo& foo = *i;
if (foo.somethingIsTrue()) // True for most elements
std::cout << index << ": " << foo << std::endl;
}
After discovering BOOST_FOREACH, I shortened this to:
typedef std::vector<Foo> FooVec;
FooVec fooVec;
int index = -1;
BOOST_FOREACH( Foo& foo, fooVec )
{
++index;
if (foo.somethingIsTrue()) // True for most elements
std::cout << index << ": " << foo << std::endl;
}
Is there a better or more elegant way to iterate over STL vectors when both reference to the vector element and its index is required?
I am aware of the alternative: for (int i = 0; i < fooVec.size(); ++i)
But I keep reading about how it is not a good practice to iterate over STL containers like this.