Search This Blog

Wednesday, October 21, 2009

C++, size_type is unsigned value type

In the STL of C++, the type of size_type is unsigned. It is a big pitfall for the use of vector, string, and for the methods that return size_type. Remember this,

Do not treat the size_type as int or unsiged, because size_type aren't always int or unsigned int, double, etc.

For example.

vector v; //a vector with size = 0
v.size(); // return 0;
v.size() -1 ; // return the largest unsigned value of integer type
// because there is no such thing as "-1" for unsigned int

so, we cannot just directly use the size_type as index.

//whoops! if v is empty, v.size() -1 is 4,294,967,295 on 32 big machine
or 18446744073709551615 on a 64 big machine
for(int i = 0; i < v.size() -1; i++)

you can do a cast so you can work on them as a normal index
for (int i =0; i <>(v.size())-1; i++)

or directly check them like
if (s.find("hello") == std::string::npos)

No comments: