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_step
和col_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.