C++:从vector<vector<T>>得到T** [英] C++: Getting T** from vector<vector<T>>
问题描述
我正在与需要 float**
类型的 2D 数组的 C 库交互,其大小在运行时确定.我想使用诸如 std::vector 之类的 STL 容器来管理此内存,但是 vector
给出了 vector
,而不是 float**
.我能做什么?
I'm interfacing with a C library that needs a 2D array of type float**
, whose size is determined at runtime. I'd like to use an STL container such as std::vector to manage this memory, but vector<vector<float>>::data()
gives vector<float>*
, not float**
. What can I do?
推荐答案
您可以创建一个新的 vector,其中包含指向由内部 vector 管理的所有内部数组的指针你的向量向量:
You could create a new vector holding the pointers to all the internal arrays managed by the inner vector of your vector of vectors:
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
注意:
显然,如果您更改向量,则需要重建指针向量,因为地址很可能会更改.
Obviously if you change your vector you will need to rebuild your pointer vector because the addresses may well change.
您可以通过一些包装函数即时重建它,如下所示:
You can either rebuild it on the fly through some wrapper function like so:
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
来封装两个向量,并在主要向量在其维度中的容量增加时更新指针向量.
Or else (my favorite) build a wrapper class
to encapsulate both vectors and update the pointer vector whenever the primary vector increases in capacity in one of its dimensions.
这篇关于C++:从vector<vector<T>>得到T**的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!