我正在与需要类型为 的二维数组的 C 库交互float**
,其大小在运行时确定。我想使用诸如 std::vector 之类的 STL 容器来管理此内存,但vector<vector<float>>::data()
给出的是vector<float>*
,而不是float**
. 我能做什么?
你可以创建一个新的载体保持指针由内部管理的所有内部阵列矢量您的载体的载体:
void old_c_function(float** floats, std::size_t X, std::size_t Y)
{
for(auto x = 0U; x < X; ++x)
for(auto y = 0U; y < Y; ++y)
std::cout << "[" << x << ", " << y << "] = " << floats[x][y] << '\n';
}
int main()
{
std::vector<std::vector<float>> v =
{
{1.2, 3.4, 5.6},
{7.8, 9.0, 1.2},
};
// create a new vector to hold the pointers to the arrays
// managed by the internal vectors
std::vector<float*> v_ptrs;
v_ptrs.reserve(v.size());
// add the addresses of all the arrays to the new vector
std::for_each(std::begin(v), std::end(v),
[&v_ptrs](auto& v){ v_ptrs.push_back(v.data()); });
// call your legacy function using your pointer vector
old_c_function(v_ptrs.data(), v.size(), v.front().size());
}
输出:
[0, 0] = 1.2
[0, 1] = 3.4
[0, 2] = 5.6
[1, 0] = 7.8
[1, 1] = 9
[1, 2] = 1.2
笔记:
显然,如果你改变你的向量,你将需要重建你的指针向量,因为地址可能会改变。
您可以通过一些包装函数即时重建它,如下所示:
void new_wrapper_function(std::vector<std::vector<float>>& v)
{
// create a new vector to hold the pointers to the arrays
// managed by the internal vectors
std::vector<float*> v_ptrs;
v_ptrs.reserve(v.size());
// add the addresses of all the arrays to the new vector
std::for_each(std::begin(v), std::end(v)
[&v_ptrs](auto& v){ v_ptrs.push_back(v.data()); });
// call your legacy function using your pointer vector
old_c_function(v_ptrs.data(), v.size(), v.front().size());
}
或者(我最喜欢的)构建一个包装器class
来封装这两个向量,并在主向量在其维度之一的容量增加时更新指针向量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句