I am working on a program that will use structures which contain vectors of vectors (a jagged matrix essentially). I am told that vectors load their content on the heap; is this true? What dictates the maximum size of my vector before I get a segfault; how much of my vector is stored on the stack?
Suppose I have a structure, which contains a vector of vectors:
1 2 3 4 5 6 7 8 9 10
struct mystruct{
vector<vector<float> > myvec;
};
int main() {
int num1 = 1234, num2 = 1234; // these can get very large
mystruct a;
a.mycec.resize(num1)
for (int i=0; i!=myvec.size(); i++) a.myvec[i].resize(num2);
}
This is basically what I'm doing at the moment (I've just moved over from using arrays to achieve similar functionality, but now that I need my matrix to be jagged I've opted for the arrays of arrays.
Is this going to give me problems? Should I "new" the vectors instead?
A vector of pointers to vectors generally perform better because you save several copy constructor calls, but that alone shouldn't weigh too much unless you'd be modifying the vector frequently.
Yes, vectors allocate memory from the heap to store their elements. How much of a vector goes into the stack? I would say sizeof(std::vector<std::vector<float>>). How much can a vector hold? I don't know. I think the vector can tell you. Look up the vector class in this site's reference.
Ok, so the amount of memory that a vector occupies in the stack is a function of only its content type, not the length? I just wanted to make sure that I'm not going to run into problems when the size of my vector exceeds 2MB.
Could you explain why a vector of pointers would perform better? Wouldn't the number of operations required to make or modify such a vector be the same? If not, why?
Depends on how you use the vector. If you keep inserting elements in the middle of the vector, then the actual move of the current elements is done by copy-constructing the elements in reverse order. Copy-constructing an entire element (a vector of floats in your case) is much more costly and complex than copy-constructing a simple pointer.
If you don't keep inserting or erasing in the middle of the vector, then you probably wouldn't even notice a performance hit by using a vector of vectors of floats.