C ++ vector< vector< double> >加倍** [英] C++ vector<vector<double> > to double **

查看:84
本文介绍了C ++ vector< vector< double> >加倍**的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将类型vector<vector<double> >的变量传递给函数F(double ** mat, int m, int n). F函数来自另一个库,因此我没有更改它的选择.有人可以给我一些提示吗?谢谢.

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.

推荐答案

vector<vector<double>>double**是完全不同的类型.但是有可能在另一个存储一些双指针的向量的帮助下提供此功能:

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

起作用的原因之一是因为std::vector保证所有元素都连续存储在内存中.

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

如果可能,请考虑更改功能的签名.通常,矩阵在内存中线性布置.这意味着,可以使用类型为double*的一些基本指针p作为左上角的系数以及一些基于行和列的计算线性索引(例如p[row*row_step+col*col_step]其中row_stepcol_step是与布局有关的偏移量.标准库在这类数据结构方面并没有提供任何帮助.但是您可以尝试使用Boost的multi_array或GSL的multi_span来解决这个问题.

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.

这篇关于C ++ vector&lt; vector&lt; double&gt; &gt;加倍**的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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