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

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

    The cleanest way of iterating through a vector is via iterators:

    for (auto it = begin (vector); it != end (vector); ++it) {
        it->doSomething ();
    }
    

    or (equivalent to the above)

    for (auto & element : vector) {
        element.doSomething ();
    }
    

    Prior to C++0x, you have to replace auto by the iterator type and use member functions instead of global functions begin and end.

    This probably is what you have seen. Compared to the approach you mention, the advantage is that you do not heavily depend on the type of vector. If you change vector to a different "collection-type" class, your code will probably still work. You can, however, do something similar in Java as well. There is not much difference conceptually; C++, however, uses templates to implement this (as compared to generics in Java); hence the approach will work for all types for which begin and end functions are defined, even for non-class types such as static arrays. See here: How does the range-based for work for plain arrays?

提交回复
热议问题