Convert 2D vector to 2d array

爷,独闯天下 提交于 2021-02-11 12:16:34

问题


I have some C++ code that uses a 2D vector and needs to call an external library that uses a pointer the array with rows and col as parameters. So what I need to do is convert my 2d vector into a format that I can shove into foo((float *)data, int rows, int cols).

So 2D Vector data ---code---> foo((float *), int row, int cols)

Trying to convert the 2d vector to a 2d array wasn't working very well using Converting 2D vector to 2D array This example uses double pointers and I don't know how to convert into a single pointer with rows and cols:

vector<vector<float>> test_vect{ {1.1,2.1,3.1}, {4.1,5.1,6.1}, {7.1,8.1,9.1}, {10.1,11,12.3}, {13.1,14.1,15.1}, {16.1,17.1,18.1}};

float* getDataAsArray(vector<vector <float>> data) {
    float** temp;
    int r =  data.size();
    int c = data[0].size();
    temp = new float*[r];
    for(unsigned i=0; (i < r); i++) { 
        temp[i] = new float[c];
        for(unsigned j=0; (j < c); j++) {
            temp[i][j] = data[i][j];
        }
    }
    float* arr = *temp;
    return arr; 
}

This isn't working as I lose state information(it only prints the first row). This is my verification code that I pass my output to.

void printMatrix(float *matrix, int rows, int cols)
{
    int i, j;
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            cout << *((matrix+i*cols)+j) << " ";
        }
        cout << "\n";
    }
}

Any suggestions?


回答1:


You can flatten the vector

vector<float> flat_vect =
        accumulate(test_vect.begin(), test_vect.end(),
                   vector<float>(),
                   [](vector<float>& a, vector<float>& b) {
                       a.insert(a.end(), b.begin(), b.end());
                       return a;
                   });

and then pass flattened version's data:

foo(flat_vect.data(), 6, 3);


来源:https://stackoverflow.com/questions/64396609/convert-2d-vector-to-2d-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!