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
The book you’re reading states that if you want to extract the size of a vector of type double (for example), you should do something like:
vector::size_type vector_size;
vector_size = myVector.size();
Whereas in Java you might do
int vector_size;
vector_size = myVector.size();
Both are inferior options in C++. The first is extremely verbose and unsafe (mostly due to implicit promotions). The second is verbose and extremely unsafe (due to number range).
In C++, do
ptrdiff_t const vectorSize = myVector.size();
Note that
ptrdiff_t
, from the stddef.h
header, is a signed type that is guaranteed large enough.
Initialization is done in the declaration (this is better C++ style).
The same naming convention has been applied to both variables.
In summary, doing the right thing is shorter and safer.
Cheers & hth.,