Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vector<vector<double> > to double **

I'm trying to pass a variable of type vector<vector<double> > to a function F(double ** mat, int m, int n). The F function comes from another lib so I have no option of changing it. Can someone give me some hints on this? Thanks.

like image 963
stacker Avatar asked Jan 23 '11 20:01

stacker


3 Answers

vector<vector<double>> and double** are quite different types. But it is possible to feed this function with the help of another vector that stores some double pointers:

#include <vector>

void your_function(double** mat, int m, int n) {}

int main() {
    std::vector<std::vector<double>> thing = ...;
    std::vector<double*> ptrs;
    for (auto& vec : thing) {
        //   ^ very important to avoid `vec` being
        // a temporary copy of a `thing` element.
        ptrs.push_back(vec.data());
    }
    your_function(ptrs.data(), thing.size(), thing[0].size());
}

One of the reasons this works is because std::vector guarantees that all the elements are stored consecutivly in memory.

If possible, consider changing the signature of your function. Usually, matrices are layed out linearly in memory. This means, accessing a matrix element can be done with some base pointer p of type double* for the top left coefficient and some computed linear index based on row and columns like p[row*row_step+col*col_step] where row_step and col_step are layout-dependent offsets. The standard library doesn't really offer any help with these sorts of data structures. But you could try using Boost's multi_array or GSL's multi_span to help with this.

like image 73
sellibitze Avatar answered Sep 30 '22 16:09

sellibitze


The way I see it, you need to convert your vector<vector<double> > to the correct data type, copying all the values into a nested array in the process

A vector is organised in a completely different way than an array, so even if you could force the data types to match, it still wouldn't work.

Unfortunately, my C++ experience lies a couple of years back, so I can't give you a concrete example here.

like image 36
Dave Vogt Avatar answered Sep 30 '22 16:09

Dave Vogt


Vector< Vector< double> > is not nearly the same as a double pointer to m. From the looks of it, m is assumed to be a 2-dimensional array while the vector is could be stored jagged and is not necessarily adjacent in memory. If you want to pass it in, you need to copy the vector values into a temp 2dim double array as pass that value in instead.

like image 40
Michael Dorgan Avatar answered Sep 30 '22 18:09

Michael Dorgan