C++ vectorlt;vectorlt;doublegt; gt; to double **(C++向量lt;vectorlt;doublegt;gt;加倍**)
问题描述
我正在尝试传递 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 或 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<double>>加倍**的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++向量<vector<double>>加倍**
- 近似搜索的工作原理 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01
