Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...