C++ Vector – Understanding Vector Size Types

c++intvector

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?

Best Answer

C++ is a language for library writing*, and allowing the author to be as general as possible is one of its key strengths. Rather than prescribing the standard containers to use any particular data type, the more general approach is to decree that each container expose a size_type member type. This allows for greater flexibility and genericity. For example, consider this generic code:

template <template <typename...> Container, typename T>
void doStuff(const Container<T> & c)
{
  typename Container<T>::size_type n = c.size();
  // ...
}

This code will work on any container template (that can be instantiated with a single argument), and we don't impose any unnecessary restrictions on the user of our code.

(In practice, most size types will resolve to std::size_t, which in turn is an unsigned type, usually unsigned int or unsigned long -- but why should we have to know that?)

*) I'm not sure what the corresponding statement for Java would be.

Related Question