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.
for (size_t i = 0; i < vec.size(); i++)
elem = vec[i];
Vectors are a thin wrapper over C arrays; whether you use iterators or indexes, it's just as fast. Other data structures are not so forgiving though, for example std::list.
You can always compute the index in the loop:
std::size_t index = std::distance(fooVec.begin(), i);
For a vector, this is quite likely to be implemented as a single pointer subtraction operation, so it's not particularly expensive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With