Search code examples
c++multidimensional-arraydoubledynamic-memory-allocation

C++: Dynamically growing 2d array


I have the following situation solved with a vector, but one of my older colleagues told me in a discussion that it would be much faster with an array.

I calculate lots (and I mean lots!) of 12-dimensional vectors from lots of audio files and have to store them for processing. I really need all those vectors before I can start my calculation. Anyhow, I can not predict how many audios, and I can not predict how many vectors are extracted from each audio. Therefor I need a structure to hold the vectors dynamically.

Therefor I create a new double array for each vector and push it to a vector.

I now want to face and test, if my colleague is really right that the calculation can be boosted with using also an array instead of a vector for storing.

vector<double*>* Features = new vector<double*>();
double* feature = new double[12];
// adding elements
Features->push_back(features);

As far as i know to create dynamically 2d array I need to know the count of rows.

double* container = new double*[rows];
container[0] = new double[12];
// and so on..

I know rows after processing all audios, and I don't want to process the audio double times.

Anyone got any idea on how to solve this and append it, or is it just not possible in that way and I should use either vector or create own structure (which assumed may be slower than vector).


Solution

  • Unless have any strong reasons not to, I would suggest something like this:

    std::vector<std::array<double, 12>> Features;
    

    You get all the memory locality you could want, and all of the the automagic memory management you need.