Alex Rivera | Logout

C++ vector size types

Asked 2011-10-03T14:23:08.727
22

I just started learning C++ and have a question about vectors. The book I'm reading states that if I want to extract the size of a vector of type double (for example), I should do something like:

vector<double>::size_type vector_size;
vector_size = myVector.size();

Whereas in Java I might do

int vector_size;
vector_size = myVector.size();

My question is, why is there a type named vector::size_type? Why doesn't C++ just use int?

Edit
Report

1 Answer

2

My personal feeling about this is that it is for a better code safety/readability.

For me int is a type which conveys no special meaning: it can number apples, bananas, or anything.

size_type, which is probably a typedef for size_t has a stronger meaning: it indicates a size, in bytes.

That is, it is easier to know what a variable mean. Of course, following this rationale, there could be a lot of different types for different units. But a "buffer size" is really a common case so it somehow deserves a dedicated type.

Another aspect is code maintability: if the container suddenly changes its size_type from say, uint64_t to unsigned int for instance, using size_type you don't have to change it in every source code relying on it.

answered 2011-10-03T14:31:38.900

Your Answer