[Solved] Why does my is random access iterator have to be of type auto when i traverse a vector?


You don’t have to use auto if you don’t want to, but you can of course.

The type returned by std::vector<int>::begin() and std::vector<int>::end() is a std:vector<int>::iterator (or std:vector<int>::const_iterator, depending on context), it is not an int. You could as well have written this instead:

for(vector<int>::iterator it=vect1.begin(); it<vect1.end();it++){
    cout<<*it<<endl;
}

or

for(vector<int>::const_iterator it=vect1.begin(); it<vect1.end();it++){
    cout<<*it<<endl;
}

In either case, you don’t want to modify the contents of the vector. Regarding your examples:

  • The first for-loop is fine and works. I’ve never seen anyone use the < operator for this, rather !=.

  • The second for-loop does also work, but does nothing, as v is empty.

  • The third for-loop is nonsense, as pointed out, an iterator is returned by begin() and end(), not an integer. To access the data the iterator points to, you need to de-reference it with the * operator, as you do for the output.

Hope this helps.

Edit: One more thing. In C++, it is also advisable to use ++it instead of it++, in general for all increments in for loops.

Here is a short explanation:

++i or i++ in for loops ??

4

solved Why does my is random access iterator have to be of type auto when i traverse a vector?