Why use iterators instead of array indices?

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

    Aside from all of the other excellent answers... int may not be large enough for your vector. Instead, if you want to use indexing, use the size_type for your container:

    for (std::vector::size_type i = 0; i < myvector.size(); ++i)
    {
        Foo& this_foo = myvector[i];
        // Do stuff with this_foo
    }
    

提交回复
热议问题