简体   繁体   中英

Convert 2D vector to 2d array

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?

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);

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