Because at no stage in the first example did you declare the size of the array (so it will start ... and stay ... zero). In the first example you reserved (at least) 100 spaces so that the array could be filled by .push_back() or by .resize (maybe some others), but reserved space is not actual size. Those memory spaces will be temporarily filled with whatever you put there, but they would be overwritten as soon as you did enough push_back()s, or a suitable resize.
In the second example the size (not just the potential reserved space) is actually set to 100 in the constructor. I think (not quite sure) the members would also be defaulted to int{} or 0 as well.
The vector always has some space in reserve so it doesn't have to do a complete reallocation of memory and lots of copying every time you increase the size with push_back. I suspect every compiler has its own algorithm for how much reserve it will keep, and you might be able to change that with compile options. A bit like always keeping your bank account well in the black for those odd days of unexpected expenditure.
First, what you wrote is incorrect and dangerous;
by writing these lines:
1 2
example_vector[5] = 28;
example_vector[42] = 32;
you are trying to put 28 and 32 at indices 5 and 42 respectively witch don't even exist;
and example_vector.size() = 0
You could declare your vector like this: vector<int> example_vector(100);
that would initialize the vector with 100 zeros and example_vector.size() = 100
However,
1 2
int x = 23;
example_vector.push_back(x)
x will be added to the end of the vector at index 100 exactly and the example_vector.size()
will change to 101.
But don't worry, the vector library provides a function insert() that can be used as the following:
1 2 3 4 5 6
vector<int> example_vector(100);
int i = 2;
vector<int>::iterator it = v.begin() + i;
example_vector.insert(it, 10); // this will insert 10 at the index i=2