Why use iterators instead of array indices?

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

    STL iterators are mostly there so that the STL algorithms like sort can be container independent.

    If you just want to loop over all the entries in a vector just use the index loop style.

    It is less typing and easier to parse for most humans. It would be nice if C++ had a simple foreach loop without going overboard with template magic.

    for( size_t i = 0; i < some_vector.size(); ++i )
    {
       T& rT = some_vector[i];
       // now do something with rT
    }
    '
    

提交回复
热议问题