patterncppCritical
Iterate through a C++ Vector using a 'for' loop
Viewed 0 times
foriterateusingvectorloopthrough
Problem
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 of the
Is there a reason I don't see this in C++? Is it bad practice?
for loop is always something based on the vector. In Java I might do something like this with an ArrayList:for(int i=0; i < vector.size(); i++){
vector[i].doSomething();
}Is there a reason I don't see this in C++? Is it bad practice?
Solution
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:
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.
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.
Code Snippets
std::vector<int>::iterator it = vector.begin();Context
Stack Overflow Q#12702561, score: 137
Revisions (0)
No revisions yet.