Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

c++ - 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. 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?

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:

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<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!

The answer below is still valid if you do not use C++11!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...