[英]How to convert vector<vector<int>>to int**?
vectoris easy to obtain int* through vector::data(), so how to convert vector<vector>to int**? vector很容易通过vector::data()得到int*,那么如何把vector<vector>转换成int**呢?
int main(int argc, char *argv[])
{
std::vector<std::vector<int>> temp {{1,2,3},{4,5,6}};
int **t;
t = reinterpret_cast<int **>(std::data(temp));
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
std::cout << t[i][j] << " ";
}
}
}
// out : 1 2 3 0 0 0
It's obviously wrong.显然是错误的。
There is a simple "trick" to create the pointer that you need, as a temporary workaround while the code is being refactored to handle standard containers (which is what I really recommend that you should do).有一个简单的“技巧”可以创建您需要的指针,作为重构代码以处理标准容器时的临时解决方法(这是我真正建议您应该做的)。
The vectors data
function returns a pointer to its first element.向量data
function 返回指向其第一个元素的指针。 So if we have a std::vector<int>
object, then its data
function will return an int*
.所以如果我们有一个std::vector<int>
object,那么它的data
function 将返回一个int*
。 That puts us about halfway to the final solution.这使我们接近最终解决方案的一半。
The second half comes by having a std::vector<int*>
, and using its data
function to return an int**
.下半部分有一个std::vector<int*>
,并使用其data
function 返回一个int**
。
Putting this together, we create a std::vector<int*>
with the same size as the original std::vector<...>
object, and then initialize all elements to point to the sub-vectors:将它们放在一起,我们创建了一个与原始std::vector<...>
std::vector<int*>
,然后初始化所有元素以指向子向量:
std::vector<std::vector<int>> temp;
// ...
// Create the vector of pointers
std::vector<int*> pointer_vector(temp.size());
// Copy the pointers from the sub-vectors
for (size_t i = 0; i < temp.size(); ++i)
{
pointer_vector[i] = temp[i].data();
}
After the above loop, then you can use pointer_vector.data()
to get the int**
pointer you need.在上面的循环之后,然后你可以使用pointer_vector.data()
来获取你需要的int**
指针。
Until you have refactored the code, you could put this in an overloaded function that does the conversion and calls the actual function:在重构代码之前,您可以将它放在一个重载的 function 中,它会进行转换并调用实际的 function:
// The original function
void some_function(int**);
// Creates a vector of pointers, and use it for the
// call of `some_function(int**)`
void some_function(std::vector<std::vector<int>> const& actual_vector);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.