Sign in to follow this  

STL Signed/Unsigned mismatch

This topic is 4383 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Say I'm trying to loop through an std::vector. I might have code like this:
for(int i=0; i<vec.size(); i++) {
...
}
Then the compiler gives me a warning about the comparison between the signed i and unsigned vec.size(). Throughout the course of my code I have about 100 of these warnings and I was wondering whether or not they had any real bearing on anything.

Share this post


Link to post
Share on other sites
When just looping those warnings are usually benign, but you should consider switching to a unsigned variable anyways. Alterantely, you can use iterators to loop through the vector.

Share this post


Link to post
Share on other sites
Hello !

You can write

for (std::vector<mytype>::size_type i=0; i<vec.size(); i++) {
...
}

Or (simpler, since finnaly ti will resolve to the same thing)

for (size_t i=0; i<vec.size(); i++) {
...
}

The vector<>::size() methode returns an unsigned int (it makes not sense to return a signed one).

But unless you are dealing with very large vectors (more than 231 entries), your code will work correctly.

(edit: C'mon, SiCrane, type slower please! [smile])

HTH,

Share this post


Link to post
Share on other sites

This topic is 4383 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this