How do I convert a std::vector
to a double array[]
?
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.
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.
You can do some what like this
vector <int> id;
vector <double> v;
if(id.size() > 0)
{
for(int i = 0; i < id.size(); i++)
{
for(int j = 0; j < id.size(); j++)
{
double x = v[i][j];
cout << x << endl;
}
}
}
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];
If you have a function, then you probably need this:foo(&array[0], array.size());
. If you managed to get into a situation where you need an array then you need to refactor, vectors are basically extended arrays, you should always use them.
For C++11, vector.data() will do the trick.