Why use iterators instead of array indices?

前端 未结 27 2101
萌比男神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:24

    If you have access to C++11 features, then you can also use a range-based for loop for iterating over your vector (or any other container) as follows:

    for (auto &item : some_vector)
    {
         //do stuff
    }
    

    The benefit of this loop is that you can access elements of the vector directly via the item variable, without running the risk of messing up an index or making a making a mistake when dereferencing an iterator. In addition, the placeholder auto prevents you from having to repeat the type of the container elements, which brings you even closer to a container-independent solution.

    Notes:

    • If you need the the element index in your loop and the operator[] exists for your container (and is fast enough for you), then better go for your first way.
    • A range-based for loop cannot be used to add/delete elements into/from a container. If you want to do that, then better stick to the solution given by Brian Matthews.
    • If you don't want to change the elements in your container, then you should use the keyword const as follows: for (auto const &item : some_vector) { ... }.

提交回复
热议问题