I am just learning C++ and I am using Accelerated C++.
In a vector example, the writer used the following code;
typedef vector<double>::size_type vec_sz;
vec_sz size = homework.size;
I know typedef vector<double>::size_type vec_sz;
is so that he doesn't have to write the next command as vector<double>::size_type size = homework.size;
, but my question is why didn't he just declare size
as an integer instead?
int size = homework.size;
Is this because we are using a vector?
If so, does that mean that the values returned by vector iterators cannot be stored in regular variables?
why didn't he just declare size as an integer?
Because integer is not the correct type to store vector's size, for two reasons:
int
is allowed to be negative; size of a vector is non-negativeint
may not be large enough to hold maximal vector sizeint
would work fine for small vectors, but for a general approach you should use vector<T>::size_type
. Note that the type is unsigned, so you need to be careful when iterating by index back to front.
does that mean that the values returned by vector iterators cannot be stored in regular variables?
Iterators are not of type vector<T>::size_type
, it is separate data type altogether.
Firstly, std::vector::size_type
is not int
.
Unsigned integral type (usually
std::size_t
)
And
std::size_t
is the unsigned integer type of the result of thesizeof
operator as well as thesizeof...
operator and thealignof
operator (since C++11).
Secondly, from c++11 you can use auto specifier
to deduce the type automatically.
auto size = homework.size();
BTW: homework.size
seems weird, you might mean homework.size()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With