Edit: The below question was answered by this. I have a new updated question, is it any more efficient to use: (my friend said it is inefficient to put a vector of a vector because it uses sequential memory and to realloc when you push_back means it takes more time to find the location where a chunk of memory for the entire large vector can be placed)
(where Picture is a vector of lines, Line is a vector of points)
std::vector<Point> *LineVec;
std::vector<Line> PictureVec;
versus
std::vector<Point> LineVec;
std::vector<Line> PictureVec;
struct Point{
int x;
int y;
}
I’m trying to get a vector of a vector and my friend told me that it’s inefficient to put a vector of a vector because it uses sequential memory and vector of a vector will require huge amounts of space. So what he suggested was a using a vector of a pointer vector. Therefore the inner vector looks like this. Clearly I’m very new to C++ and would appreciate any insight.
struct Shape{
int c;
int d;
}
std::vector<Shape> *intvec;
When I want to push back into this, how would I do so? Something like this?
Shape s;
s.c=1;
s.d=1;
intvec->push_back(s);
Also, I wrote an iterator to go through, however it does not seem to work, hence why I believe the above code does not work. Finally my last concern is, while the above code works, it gives really weird values for my output. Large numbers that are 7 digits long and definitely not the values I put in for s.c and s.d
for(std::vector<Shape>::iterator it=Shapes->begin();it<Shapes->end();it++){
Shape s = (*it);
std::cout << s.c << s.d << std::endl;
}
Using a vector of pointers to vectors is not more efficient than a vector of vectors. It’s less efficient, because it introduces an extra level of indirection. It also does not cause all elements of the resulting 2-d array to be allocated contiguously.
The reason is that a vector is practically a pointer to an array, in the sense that a
vector<T>is implemented roughly asso that a vector of vectors behaves, performance-wise, like a dynamic array of pointers to arrays.
[Note: I can’t quote the C++ standard chapter and verse, but I’m pretty sure it constrains
std::vector‘s operations and complexity in such a way that the above is the only practical way of implementing it.]