Re: help with vector<vector<double>>
On Aug 9, 3:18 pm, "Bo Persson" <b...@gmb.dk> wrote:
T. Crane wrote:
:: 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?
About right, yes. It also uses additional features, like for each time
the data is copied it allocates increasingly larger and larger blocks
of memory, so that it will not have to make additional copies for a
long time.
If your real sizes are 10 and 15, you definitely don't have to worry.
If you have 100s of millions of elements, you might have to. But you
will have to try it out first!
Bo Persson
My real sizes are:
100 data points cubed x 2 (two channels) x ~ 8 (different parameter
sets) ~= 16 million data points. Each data point is a 4 element
vector.
So, I'll try this first (as an example):
#include <vector>
int nColumns = 2;
int nRows = 3;
vector<float> v1(3),v2(3);
vector<vector<float>> m(2);
v1.push_back(0.23);
v1.push_back(0.36);
v1.push_back(1.54);
v2.push_back(0.76);
v2.push_back(0.86);
v2.push_back(2.92);
m.push_back(v1);
m.push_back(v2);
First off, is this the "recommended" way of populating a 2D vector?
Second, if I find that I really, really want to use vector::reserve(),
how would I do it for a 2D vector?
#include <vector>
vector<float> v;
v.reserve(50);
vector<vector<float>> m;
m.reserve(...?) How do I tell it to reserve enough memory to hold n
vector elements like v?
thanks again for your help,
trevis