So why is that? I would expect reserve to take up the needed amount of memory, without actually creating any objects. I'm aware that I can initialize the vector with a size, but as far as I understand that creates as many default objects as the size given, and for large lists this doesn't work for me, as it would take up an awful lot of memory for my project.
Disch no, reserve is exactly what I want. If I have a big vector, then I will get a lot of default objects, which I won't need. And the first example DOES work, I compiled it and ran it, and outputted b to the console as well after assigning different values, and it outputted them as expected.
If you want to have a vector that has an element myVector[n], then you have to also have elements myVector to myVector[n-1]. That's how vectors work. You can't have it have only certain elements, without having all the other elements present (even if they're default-initialised) up to the size of the vector.
It sounds like what you really want is a std::map which uses an int as the key. That will allow you to have elements for each non-contiguous key you choose, without requiring other elements to be present.
> And the first example DOES work, I compiled it and ran it,
> and outputted b to the console as well after assigning different values,
> and it outputted them as expected.
Undefined behaviour is undefined. Please don't invoke it.
Array index goes from 0 to size-1. Your vector is empty, its size is 0.