tags:

views:

179

answers:

4

I want to convert vector of double to array of double. Can any one help me to do this

+2  A: 
vector<double> thevector;
//...
double *thearray = &thevector[0];

This is guaranteed to work by the standard, however there are some caveats: in particular take care to only use thearray while thevector is in scope.

...and make sure the vector isn't `empty()`, otherwise this would invoke the dreaded UB.
sbi
+10  A: 

There's a fairly simple trick to do so, since the spec now guarantees vectors store their elements contiguously:

std::vector<double> v;
double* a = &v[0];
Michael Mrozek
I tried this method. but all elements in the vector didn't copy to array. How to copy all the elements to the array?
ganuke
@ganuke You're not copying, you're making a pointer that points to the actual array the vector is using internally. If you want to copy [GMan's answer](http://stackoverflow.com/questions/2923272/how-to-convert-vector-to-array-c/2923295#2923295) explains how
Michael Mrozek
@ganuke: What is "the array"? You need to provide more information. What's the big picture?
GMan
void GMap::train( double* inputVector);this is the function I need to call. But I have a vector of double.so I need to copy that vector to a array.
ganuke
@ganuke You don't, you just need a `double*` that points to the same data. This answer works for exactly that case
Michael Mrozek
oops.. is that so.. Then its ok. I'm new to C++ programing. thanks for helping me.
ganuke
@ganuke You should [accept an answer](http://meta.stackoverflow.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) if your problem is solved
Michael Mrozek
My problem is solved. Thanks for every one.
ganuke
@ganuke: If you found an answer solved the problem, click the green check mark next to it to indicate so.
GMan
+2  A: 

Vectors effectively are arrays under the skin. If you have a function:

void f( double a[]);

you can call it like this:

vector <double> v;
v.push_back( 1.23 )
f( &v[0] );

You should not ever need to convert a vector into an actual array instance.

anon
I think you meant `f( ` for your last line
Michael Mrozek
+3  A: 

What for? You need to clarify: Do you need a pointer to the first element of an array, or an array?

If you're calling an API function that expects the former, you can do do_something(&v[0], v.size()), where v is a vector of doubles. The elements of a vector are contiguous.

Otherwise, you just have to copy each element:

double arr[100];
std::copy(arr, arr + 100, v.begin());

Of course, ensure v actually has enough elements to copy.


Utility function, to help with arrays:

template <typename T, size_t N>
T* end(T (&pArray)[N])
{
    return &pArray[0] + N;
}

Giving:

double arr[100];
std::copy(arr, end(arr), v.begin());
GMan