Iterate through a C++ Vector using a 'for' loop

后端 未结 12 1721
天命终不由人
天命终不由人 2020-11-29 16:02

I am new to the C++ language. I have been starting to use vectors, and have noticed that in all of the code I see to iterate though a vector via indices, the first parameter

12条回答
  •  暖寄归人
    2020-11-29 16:28

    There's a couple of strong reasons to use iterators, some of which are mentioned here:

    Switching containers later doesn't invalidate your code.

    i.e., if you go from a std::vector to a std::list, or std::set, you can't use numerical indices to get at your contained value. Using an iterator is still valid.

    Runtime catching of invalid iteration

    If you modify your container in the middle of your loop, the next time you use your iterator it will throw an invalid iterator exception.

提交回复
热议问题