将std :: vector转换为数组

编程入门 行业动态 更新时间:2024-10-11 05:21:20
本文介绍了将std :: vector转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个库,期望一个数组,并填充它。我想使用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转换为数组

本文发布于:2023-11-05 18:18:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561528.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   转换为   std   vector

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!