Matt
Matt

Reputation: 3557

vector<double>::size_type vs. double

Why would you use vector<double>::size_type in a for loop rather than just, say, double? I've never really messed with C++ vectors before and I was reading this website's tutorial on them. The author writes their for loop as,

for (vector<double>::size_type i = 0; i < 20; i++)
{
    cout << "Enter marks for student #" << i+1
         << ": " << flush;
    cin >> student_marks[i];
}

I can see that it works both ways, but why would you use them in the above way rather than just simply declaring your counter (i) as a primitive type? I saw this older SO post but I'm still not sure.

Upvotes: 0

Views: 485

Answers (2)

The fundamental types can be divided into floating point and arithmetic types. Floating point types are really bad to model an index, since the main purpose is to be able to represent values that are not integral in nature. What would be the result of indexing a vector with a value of say 1.75? Either you index into the vector at position 1 or 2, but there is no object at position 1.75.

A different issue arises with the range of the possible values that can be used to index the container. There are different integral types like unsigned char or short that while they naturally fit the purpose of indexing might have a range much smaller than the size of the container and thus cannot be used to access any position in the vector, and some might have values that are not valid indices, like -1. Both of these are issues with double: it can represent negative values which make no sense as an index, and it cannot precisely represent all of the values in an uint64_t (which is a common type for size_type in 64bit architectures).

The standard library requires that each container provides a nested type (or typedef) that can be used to index into the container. This will be an integral unsigned type of a large enough size to refer to any element in the container. Using the nested typedef means that whenever you build your program with a different implementation, in a different architecture or with a different compiler it will always be the right indexing type.

Upvotes: 1

BlackMamba
BlackMamba

Reputation: 10252

If you want your code to be portable and maintainable, you have to use the size_type defined in the container to index.

If you want the 99% solution, then currently, at least on gcc, all size_types are nothing more than typedefs of size_t (which is an unsigned int), so you could use size_t. But, understand that this could change in the future and your code could stop working or stop compiling.

Upvotes: 2

Related Questions