Why use iterators instead of array indices?

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

    The second form represents what you're doing more accurately. In your example, you don't care about the value of i, really - all you want is the next element in the iterator.

    0 讨论(0)
  • 2020-11-22 16:35

    It's part of the modern C++ indoctrination process. Iterators are the only way to iterate most containers, so you use it even with vectors just to get yourself into the proper mindset. Seriously, that's the only reason I do it - I don't think I've ever replaced a vector with a different kind of container.


    Wow, this is still getting downvoted after three weeks. I guess it doesn't pay to be a little tongue-in-cheek.

    I think the array index is more readable. It matches the syntax used in other languages, and the syntax used for old-fashioned C arrays. It's also less verbose. Efficiency should be a wash if your compiler is any good, and there are hardly any cases where it matters anyway.

    Even so, I still find myself using iterators frequently with vectors. I believe the iterator is an important concept, so I promote it whenever I can.

    0 讨论(0)
  • 2020-11-22 16:36

    I don't use iterators for the same reason I dislike foreach-statements. When having multiple inner-loops it's hard enough to keep track of global/member variables without having to remember all the local values and iterator-names as well. What I find useful is to use two sets of indices for different occasions:

    for(int i=0;i<anims.size();i++)
      for(int j=0;j<bones.size();j++)
      {
         int animIndex = i;
         int boneIndex = j;
    
    
         // in relatively short code I use indices i and j
         ... animation_matrices[i][j] ...
    
         // in long and complicated code I use indices animIndex and boneIndex
         ... animation_matrices[animIndex][boneIndex] ...
    
    
      }
    

    I don't even want to abbreviate things like "animation_matrices[i]" to some random "anim_matrix"-named-iterator for example, because then you can't see clearly from which array this value is originated.

    0 讨论(0)
提交回复
热议问题