Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did he use "typedef vector<double>::size_type" instead of using "int"

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?

like image 882
Olaniyi Jinadu Avatar asked Apr 20 '16 01:04

Olaniyi Jinadu


2 Answers

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-negative
  • Even an unsigned int may not be large enough to hold maximal vector size

int 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.

like image 57
Sergey Kalinichenko Avatar answered Nov 05 '22 17:11

Sergey Kalinichenko


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 the sizeof operator as well as the sizeof... operator and the alignof 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().

like image 39
songyuanyao Avatar answered Nov 05 '22 17:11

songyuanyao