C++ vector > to double **

2019-02-17 02:06发布

问题:

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.

回答1:

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:

vector<vector<double> > thing = ...;
vector<double*> ptrs (thing.size());
for (unsigned i=0, e=ptrs.size(); i<e; ++i) {
    ptrs[i] = &(thing[i][0]); // assuming !thing[i].empty()
}
your_function(&ptrs[0],...);

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



回答2:

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.



回答3:

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.