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

后端 未结 12 1732
天命终不由人
天命终不由人 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:44

    Is there any reason I don't see this in C++? Is it bad practice?

    No. It is not a bad practice, but the following approach renders your code certain flexibility.

    Usually, pre-C++11 the code for iterating over container elements uses iterators, something like:

    std::vector::iterator it = vector.begin();
    

    This is because it makes the code more flexible.

    All standard library containers support and provide iterators. If at a later point of development you need to switch to another container, then this code does not need to be changed.

    Note: Writing code which works with every possible standard library container is not as easy as it might seem to be.

提交回复
热议问题