简体   繁体   中英

Initialization of vector of vector is very slow

I have a vector of vectors and I am trying to initialize it as follows:

vector<vector<float> > matrix(numberOfRows, vector<float> (numberOfCols));

But this line lasts about 0.89 where the numberOfRows and numberOfCols are:

const uint32_t numRows = 10000;
const uint32_t numCols = 20000;

Whereas initializing dynamics array with the following code take 0.04 sec to execute:

float **matrix = new float*[numberOfRows];
for (size_t i = 0; i < numberOfRows; ++i)
    matrix[i] = new float[numberOfCols];

Am I doing something wrong is there any faster way to initialize that vector?

Edit:

As for the questions:

I used g++-4.5 to test using O3 optimization level with default standard.

The difference is that the vector is initialized to zero, while the dynamic array is not. With 200 million values, this is noticable.

You have the option of delaying initialization of the vector rows until you have real values to assign them, by not expanding the columns in the initialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM