What is the correct way of iterating over a vector in C++?
Consider these two code fragments, this one works fine:
for (unsigned i=0; i < polygon.size(); i++) {
sum += polygon[i];
}
and this one:
for (int i=0; i < polygon.size(); i++) {
sum += polygon[i];
}
which generates warning: comparison between signed and unsigned integer expressions
.
I'm new in the world of C++, so the unsigned
variable looks a bit frightening to me and I know unsigned
variables can be dangerous if not used correctly, so – is this correct?
Best Answer
For iterating backwards see this answer.
Iterating forwards is almost identical. Just change the iterators / swap decrement by increment. You should prefer iterators. Some people tell you to use
std::size_t
as the index variable type. However, that is not portable. Always use thesize_type
typedef of the container (While you could get away with only a conversion in the forward iterating case, it could actually go wrong all the way in the backward iterating case when usingstd::size_t
, in casestd::size_t
is wider than what is the typedef ofsize_type
):Using std::vector
Using iterators
Important is, always use the prefix increment form for iterators whose definitions you don't know. That will ensure your code runs as generic as possible.
Using Range C++11
Using indices
Using arrays
Using iterators
Using Range C++11
Using indices
Read in the backward iterating answer what problem the
sizeof
approach can yield to, though.