将2D向量转换为2D数组 [英] Convert 2D vector to 2d array

查看:57
本文介绍了将2D向量转换为2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些使用2D向量的C ++代码,需要调用一个外部库,该库使用一个指针,该指针将具有行和col的数组作为参数.因此,我需要做的是将2d向量转换为可以推入 foo((float *)data,int rows,int cols).

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

因此2D矢量数据---代码--->foo((float *),int row,int cols)

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

使用尝试将2d向量转换为2d数组效果不佳.将2D向量转换为2D数组此示例使用双指针,但我不知道如何将其转换为带有行和列的单个指针:

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";
    }
}

有什么建议吗?

推荐答案

您可以展平矢量

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

这篇关于将2D向量转换为2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆