Search code examples
c++arraysvectordynamic-arrayspush-back

array instead of vector of vector, push_back() of elements. c++


I use approach of vector of vector and would like to change it into array for performance reasons. However I failed at trying to understand, how can I use array (dynamic) and push data in the end of the array, if I do not know how many data are being read during my while loop. Here snippet below. Can you please explain how to perform it on array, as push_back() is only for vector? Would be so much grateful.

std::vector<vector<double>> v1;
while (1)
{
    ..../* some code, break condition aswell*/
    vector<double> tmp;
    while ( .../*new data available*/ ) 
    {
        ...
        tmp.push_back(data);
    } 
    v1.push_back(tmp);
}

Solution

  • A std::vector<T> is a dynamic array. What might speed up your code is this:

    std::vector<vector<double>> v1;
    while (1)
    {
        ..../* some code, break condition aswell*/
        v1.push_back(vector<double>());
        while ( .../*new data available*/ ) 
        {
            ...
            v1.back().push_back(data);
        } 
    }