Why use iterators instead of array indices?

前端 未结 27 1888
萌比男神i
萌比男神i 2020-11-22 15:45

Take the following two lines of code:

for (int i = 0; i < some_vector.size(); i++)
{
    //do stuff
}

And this:

for (som         


        
27条回答
  •  忘了有多久
    2020-11-22 16:21

    I don't think it makes much difference for a vector. I prefer to use an index myself as I consider it to be more readable and you can do random access like jumping forward 6 items or jumping backwards if needs be.

    I also like to make a reference to the item inside the loop like this so there are not a lot of square brackets around the place:

    for(size_t i = 0; i < myvector.size(); i++)
    {
        MyClass &item = myvector[i];
    
        // Do stuff to "item".
    }
    

    Using an iterator can be good if you think you might need to replace the vector with a list at some point in the future and it also looks more stylish to the STL freaks but I can't think of any other reason.

提交回复
热议问题