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

Feb 5, 2012 at 4:42pm
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 Feb 5, 2012 at 7:10pm
Feb 5, 2012 at 7:10pm
bump up~
Feb 5, 2012 at 7:48pm
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.
Feb 5, 2012 at 8:12pm
Thanks, Peter87. My question is now answered!

Feb 5, 2012 at 11:40pm
This is also where the C++11 auto keyword comes in. :-)
Feb 5, 2012 at 11:54pm
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.