When they say the vector class member function size() returns an unsigned int, what exactly does that mean? I understand an insigned int is a non-negative integer, but isn't that the same as saying an unsigned int is a positive integer? According to the book i'm reading the following loop is incorrect.for (int i= 0; i < sample.size( ); i++) Apparently you need to declare the variable i as an unsigned int. My question is, if you have already intialized i as a positive integer, why should the compiler have a problem comparing the value of i to the value returned by sampe.size()?
A regular int uses 31 bits representing a number and 1 bit representing the negative sign. This has a range of -2,147,483,647 to +2,147,483,647.
An unsignedint uses that sign bit as data instead of representing a sign. This means that it uses 32 data bits which gives you larger maximum but you can't use a negative (0 to 4,294,967,295).
This is more interesting when we are looking at chars which are only 1 byte (8 bits long). A char has a range -127 to 127 while an unsignedchar has a range of 0 to 255.
> I understand an insigned int is a non-negative integer,
> but isn't that the same as saying an unsigned int is a positive integer?
Not precisely. Zero is neither positive nor negative; it is both non-positive and non-negative.
> According to the book i'm reading the following loop is incorrect.
> for (int i= 0; i < sample.size( ); i++)
In practise, the int will be converted to an unsigned integral type before the comparison is made. It would work as expected if the size of the vector is not greater than std::numeric_limits<int>::max()
> Apparently you need to declare the variable i as an unsigned int.
That would work as expected if the size of the vector is not greater than std::numeric_limits<unsignedint>::max()