Hello, welcome to the forum
This is the crucial line:
take a look at the reference -> http://www.cplusplus.com/reference/vector/vector/vector/, this is the part that relates to this situation:
explicit vector (size_type n, const allocator_type& alloc = allocator_type());
vector (size_type n, const value_type& val, const allocator_type& alloc = allocator_type());
Constructs a container with n elements. Each element is a copy of val (if provided).
This means that in this line of code you have created a vector of type
num (in case of this snippet
num = 8) elements. Vector initialises all the elements and the default value for
0. That is why in the output you get eight zeros
To fix this problem you can simply omit the
Small digression that can be ignored.
But this should lead us to a question - why there is a way to specify the number of elements at the creation time of the vector - its length is extendable, right? Right. But when you initialise vector without specifying the size then with every
push_back there might be a need to allocate memory (and this takes time). And sometimes this is what we want - sometimes we simply do not know how many elements will be in the vector.
But in case of this function, we are sure that we will
3 values. But we do not want to start with three zeros, we don’t know the values, we have to calculate them. In this scenario we can use
reserve method to allocate memory for three