Search code examples
c++for-loopvector2d-vector

Can I convert my 1D vector to a 2D vector faster than this?


The question is quite straightforward. After some trials, here is the most efficient code I found:

//For the sake of the example, I initialize every entry as zero.
vector<float> vector1D(1024 * 768, 0); 
vector<vector<float>> vector2D(768, vector<float>(1024,0));

int counter = 0;
for (int i = 0; i < 768; i++) {
    for (int j = 0; j < 1024; j++) {
        vector2D[i][j] = vector1D[counter++];
    }
}

Is there a faster way?


Solution

  • It might be faster by using memcpy, as that is the lowest possible level of an API for copying memory and is likely that there are compiler optimizations which may use specific instructions, etc. and make if faster:

    for (int i = 0; i < 768; i++) {
        memcpy(vector2D[i].data(), &vector1D[i * 1024], sizeof(float) * 1024);
    }
    

    Keep in mind that you shouldn't be using memcpy for anything but trivially-copiable data. That is, it will work fine for float and int but not for classes as the copy constructor will not be called.