C++

Asked • 08/31/19

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

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?

1 Expert Answer

By:

Keith B. answered • 09/06/19

Tutor
4.6 (22)

Software Engineer and Math Geek

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.