Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Iteration over std::vector: unsigned vs signed index variable

What is the right 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 causes a 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?
by

3 Answers

espadacoder11
In the specific case in your example, I'd use the STL algorithms to accomplish this.

#include <numeric>

sum = std::accumulate( polygon.begin(), polygon.end(), 0 );

For a more general, but still fairly simple case, I'd go with:

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>

using namespace boost::lambda;
std::for_each( polygon.begin(), polygon.end(), sum += _1 );
pankajshivnani123
A call to vector<T>::size() returns a value of type std::vector<T>::size_type, not int, unsigned int or otherwise.

Also generally iteration over a container in C++ is done using iterators, like this.

std::vector<T>::iterator i = polygon.begin();
std::vector<T>::iterator end = polygon.end();

for(; i != end; i++){
sum += *i;
}

Where T is the type of data you store in the vector.

Or using the different iteration algorithms (std::transform, std::copy, std::fill, std::for_each et cetera).
RoliMishra
Use size_t :

for (size_t i=0; i < polygon.size(); i++)

Login / Signup to Answer the Question.