Re: help with vector<vector<double>>
On Aug 9, 1:17 pm, Philip Potter <p...@removethis.doc.ic.ac.uk> wrote:
T. Crane wrote:
#include <vector>
int nColumns = 10;
int nRows = 15;
vector<vector<double>> myData;
myData.reserve(nRows);
for (int i;i<nRows;i++){
myData[i].reserve(nColumns);
}
This code is broken. vector::reserve() doesn't actually create or
initialize objects in the vector; it only allocates space for objects
which have yet to be inserted using push_back() or whatever. As a
result, even after the myData.reserve() call, myData contains no items
and myData[i] refers to an item which doesn't exist.
As Alf says, you may not need to reserve at all. First, make it correct.
Then, only if necessary, make it faster.
Phil
OK -- that helps some. A related question then: if I have a vector
object and I don't reserve any space beforehand, as I understand it if
I push_back values into the vector, this will cause at some point the
vector object to exceed its initial capacity. At this point the
vector will identify a contiguous block of memory that is large enough
to accomodate the original vector plus the additional data. It will
then make a copy of itself and the new data into the new block of
memory. Is this basically how it works?
If it is, I call this growing the vector dynamically. This is in
contrast to reserving one chunk of memory that's big enough to hold
everything you want at the beginning and then populating it using
push_back. In this manner, there is never a reason to go out and find
a new chunk of contiguous memory.
Does this clarify what I'm getting at? And yes, I understand that I
could get it right first and then get it faster, but if I can do both
at once, why not?
thanks for your help,
trevis