I am trying to figure out why I get a SIGSEGV fault, when I try to assign an object to a vector, even when I've used reserve, when it works if I just use a primitive data type.
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.
Reserve is not what you want... you want resize. Resize will actually create a new element in the vector. Reserve will allocate space but will not create the element.
1 2 3 4 5 6 7
int main() {
vector<int> b;
b.reserve(1);
b[0] = 1; // <- BAD you are accessing b[0] which doesn't exist because the
// vector has 0 elements!
return 0;
}
Change that to resize... or push_back your elements into the vector.
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[0] 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[0] 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[0] to the console as well after assigning different values, and it outputted them as expected.
Interestingly this did not work on my machine (windows 8, VS 2010 pro edition).
> And the first example DOES work, I compiled it and ran it,
> and outputted b[0] 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.