Why use iterators instead of array indices?

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

    You might want to use an iterator if you are going to add/remove items to the vector while you are iterating over it.

    some_iterator = some_vector.begin(); 
    while (some_iterator != some_vector.end())
    {
        if (/* some condition */)
        {
            some_iterator = some_vector.erase(some_iterator);
            // some_iterator now positioned at the element after the deleted element
        }
        else
        {
            if (/* some other condition */)
            {
                some_iterator = some_vector.insert(some_iterator, some_new_value);
                // some_iterator now positioned at new element
            }
            ++some_iterator;
        }
    }
    

    If you were using indices you would have to shuffle items up/down in the array to handle the insertions and deletions.

提交回复
热议问题