Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct std::vector<double> from a double* array of known size

I have a pointer to the first element of a double array: double* p.

I also know the length of the array: n.

Is there a way I can copy this into a std::vector? Preferably using a constructor and allocator. I'd like to do something like

std::vector<double> v = std::vector(p, n);

but can't figure out which constructor is closest to this. I'm using C++11.

like image 494
P45 Imminent Avatar asked Mar 27 '14 15:03

P45 Imminent


2 Answers

std::vector<> has a constructor that takes a range. You can use it like this:

std::vector<double> v(p, p + n);
like image 84
David G Avatar answered Oct 13 '22 00:10

David G


Try

std::vector<double> v( p, p + n );

Or if the vector was already defined then

v.assign( p, p + n );

If you want to append the vector then

v.insert( v.end(), p, p + n );
like image 30
Vlad from Moscow Avatar answered Oct 13 '22 00:10

Vlad from Moscow