C++向量<vector<double>>加倍**
我正在尝试传递 vector
到函数 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
和 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
或 GS??L 的 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.
相关文章