Vector to Array

How do you convert a vector to an Array without creating a new variable of that type, i.e.:
1
2
vector<int> myVector;
int myArray[] = myVector;
When I tried this it didn't work, anyone know why?

Nor this: (int[])myVector

Anyway, the point is I need to convert a Vector to an Array like in the second example or something similar because I later need to create a pointer to it.

Any Ideas?
I think you would need to create a dynamic array and then fill it with the vector's values or use the copy algorithm
http://www.cplusplus.com/reference/algorithm/copy.html
Last edited on
I think you would need to create a dynamic array and then fill it with the vector's values or use the copy algorithm http://www.cplusplus.com/reference/algorithm/copy.html

But that would require double the amout of memory; the vector and the new array. I want to use a vector in a function which (as far as I can tell) takes arrays but not vectors. It's memcpy, when I try using copy it doesn't give the same results.
Your just going to have to deal with it using double the amount of memory unless you can re-write the function to take a vector.
In the end I found a way:

memcpy( destination, &myVector[0], sizeof( int ) * myVector.size() );

Pretty simple if you think about it. ;)
Hopefully this will be helpful to someone in the future.
Last edited on
I'm going to have to say that I don't like it. It works because a vector is guaranteed to use continuous memory, but it is still a shallow copy. The STL copy algorithm would perform assignments for each object; in case you were not just using a built-in or other simple type. I would fear that someone would copy this method and try it on another container or on a vector of more complex objects without knowing better...
Topic archived. No new replies allowed.