Why use iterators instead of array indices?

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

    No one mentioned yet that one advantage of indices is that they are not become invalid when you append to a contiguous container like std::vector, so you can add items to the container during iteration.

    This is also possible with iterators, but you must call reserve(), and therefore need to know how many items you'll append.

提交回复
热议问题