将std :: vector转换为数组 [英] Convert std::vector to array
问题描述
我有一个库,期望一个数组,并填充它。我想使用std :: vector而不是使用数组。所以代替
I have a library which expects a array and fills it. I would like to use a std::vector instead of using an array. So instead of
int array[256];
object->getArray(array);
我想这样做:
std::vector<int> array;
object->getArray(array);
但我找不到办法。是否有任何机会使用std :: vector这个?
But I can't find a way to do it. Is there any chance to use std::vector for this?
感谢阅读!
编辑:
我想对这个问题进行更新:
我在使用C ++ 11,发现了一个更好的方法。新的解决方案是使用函数std :: vector.data()获取指向第一个元素的指针。
所以我们可以这样做:
I want to place an update to this problem: I was playing around with C++11 and found a better approach. The new solution is to use the function std::vector.data() to get the pointer to the first element. So we can do the following:
std::vector<int> theVec;
object->getArray(theVec.data()); //theVec.data() will pass the pointer to the first element
向量与固定数量的元素我们更好地使用新的数据类型std ::数组(btw,因为这个原因变量名称数组,在上面的问题中使用不应该再使用了!)。
If we want to use a vector with a fixed amount of elements we better use the new datatype std::array instead (btw, for this reason the variable name "array", which was used in the question above should not be used anymore!!).
std::array<int, 10> arr; //an array of 10 integer elements
arr.assign(1); //set value '1' for every element
object->getArray(arr.data());
这两种代码变体都可以在Visual C ++ 2010中正常工作。记住:这是C ++ 11代码您将需要一个支持这些功能的编译器!
Both code variants will work properly in Visual C++ 2010. Remember: this is C++11 Code so you will need a compiler which supports the features!
如果不使用C ++ 11,下面的答案仍然有效!
The answer below is still valid if you do not use C++11!
推荐答案
是:
std::vector<int> array(256); // resize the buffer to 256 ints
object->getArray(&array[0]); // pass address of that buffer
向量中的元素
保证是连续的,就像数组一样。
Elements in a vector
are guaranteed to be contiguous, like an array.
这篇关于将std :: vector转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!