Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL: How to iterate vector while requiring access to element and its index?

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.

like image 605
Ashwin Nanjappa Avatar asked Dec 31 '25 07:12

Ashwin Nanjappa


2 Answers

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.

like image 130
CMircea Avatar answered Jan 02 '26 00:01

CMircea


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.

like image 26
James McNellis Avatar answered Jan 01 '26 23:01

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!