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
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 Container, typename T>
void doStuff(const Container & c)
{
typename Container::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.