Why use iterators instead of array indices?

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

    After having learned a little more on the subject of this answer, I realize it was a bit of an oversimplification. The difference between this loop:

    for (some_iterator = some_vector.begin(); some_iterator != some_vector.end();
        some_iterator++)
    {
        //do stuff
    }
    

    And this loop:

    for (int i = 0; i < some_vector.size(); i++)
    {
        //do stuff
    }
    

    Is fairly minimal. In fact, the syntax of doing loops this way seems to be growing on me:

    while (it != end){
        //do stuff
        ++it;
    }
    

    Iterators do unlock some fairly powerful declarative features, and when combined with the STL algorithms library you can do some pretty cool things that are outside the scope of array index administrivia.

提交回复
热议问题