when should I use "size_type" instead of "int"?

When should I use "size_type" instead of "int" to claim the type of a variable?

Similarly, should I write

1
2
3
for(vector<int>::iterator i=vec.begin(); i!=vec.end(); i++){
...
}


or

1
2
3
for(int i=vec.begin(); i!=vec.end(); i++){
...
}

?

I always have a hard time deciding to use "int" or something "type related". Can anyone explain a bit? Thanks!
Last edited on
bump up~
Look at the return type. The return type of std::vector::size() is size_type so you better use it. If you use an int you might get an warning about comparison of signed and unsigned types. I often use size_t instead of size_type because then I don't have to write the whole vector type.

begin() and end() returns an iterator so it will not work with an int.
Thanks, Peter87. My question is now answered!

This is also where the C++11 auto keyword comes in. :-)
Still good to have a good understanding of the types and not just blindly throwing auto all over the place.
Topic archived. No new replies allowed.