Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert std::vector to array

Tags:

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!

like image 856
SideEffect Avatar asked Sep 24 '10 12:09

SideEffect


People also ask

Can you convert a vector to an array in C++?

Using the transform() function to convert vector to array in C++ We can use the transform() function in C++ to apply a function to all the elements of an array. It applies the function to all the elements and stores the result in a new array.

How do you copy an element from a vector to an array?

The elements of a vector are contiguous. Otherwise, you just have to copy each element: double arr[100]; std::copy(v. begin(), v.

Can you pass a vector as an array?

Yes. Assuming v. size() > 0 , this is safe (If the vector is empty, then v[0] results in undefined behavior). The elements of a std::vector container are stored contiguously, just like in an ordinary array.


1 Answers

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.

like image 86
GManNickG Avatar answered Nov 06 '22 05:11

GManNickG