简体   繁体   English

将std :: vector转换为数组

[英]Convert std::vector to array

I have a library which expects a array and fills it. 我有一个库,需要一个数组并填充它。 I would like to use a std::vector instead of using an array. 我想使用std :: vector而不是使用数组。 So instead of 而不是

int array[256];
object->getArray(array);

I would like to do: 我想要做:

std::vector<int> array;
object->getArray(array);

But I can't find a way to do it. 但我找不到办法做到这一点。 Is there any chance to use std::vector for this? 有没有机会使用std :: vector?

Thanks for reading! 谢谢阅读!


EDIT: I want to place an update to this problem: I was playing around with C++11 and found a better approach. 编辑:我想更新这个问题:我正在玩C ++ 11并找到了更好的方法。 The new solution is to use the function std::vector.data() to get the pointer to the first element. 新的解决方案是使用函数std :: vector.data()来获取指向第一个元素的指针。 So we can do the following: 所以我们可以做到以下几点:

std::vector<int> theVec;
object->getArray(theVec.data()); //theVec.data() will pass the pointer to the first element

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(btw,因此不应再使用上面问题中使用的变量名“array”! !)。

std::array<int, 10> arr; //an array of 10 integer elements
arr.assign(1); //set value '1' for every element
object->getArray(arr.data());

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! 这两种代码变体都可以在Visual C ++ 2010中正常工作。请记住:这是C ++ 11代码,因此您需要一个支持这些功能的编译器!

The answer below is still valid if you do not use C++11! 如果你不使用C ++ 11,下面的答案仍然有效!

Yes: 是:

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. vector中的元素保证是连续的,就像数组一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM