C++ 将 std::vector 转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3787074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:44:29  来源:igfitidea点击:

Convert std::vector to array

c++stlvector

提问by SideEffect

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

我有一个需要数组并填充它的库。我想使用 std::vector 而不是使用数组。所以代替

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. 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:

编辑:我想更新这个问题:我在玩 C++11 并找到了一个更好的方法。新的解决方案是使用函数 std::vector.data() 来获取指向第一个元素的指针。所以我们可以做到以下几点:

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 代替(顺便说一句,由于这个原因,不应再使用上面问题中使用的变量名称“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,下面的答案仍然有效!

回答by GManNickG

Yes:

是的:

std::vector<int> array(256); // resize the buffer to 256 ints
object->getArray(&array[0]); // pass address of that buffer

Elements in a vectorare guaranteed to be contiguous, like an array.

avector中的元素保证是连续的,就像数组一样。