Why use iterators instead of array indices?

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

    Another nice thing about iterators is that they better allow you to express (and enforce) your const-preference. This example ensures that you will not be altering the vector in the midst of your loop:

    
    for(std::vector::const_iterator pos=foos.begin(); pos != foos.end(); ++pos)
    {
        // Foo & foo = *pos; // this won't compile
        const Foo & foo = *pos; // this will compile
    }
    

提交回复
热议问题