Sometimes it is necessary to interact with C code from a C++ program. We would then need to extract a pointer out from a vector, or vice-versa, create a vector from a pointer to data without having to worry about the extra memory management this may cause.
This one line of code will convert a pointer to an array and the number of elements in the array and into a vector from the C++ standard library:
1 2 3 4 5 |
void my_nice_function(double* pData, unsigned int number_of_elements) { std::vector<double> local_vector(pData, pData+number_of_elements); // go on and use the local_vector here!! } |
This creates a copy of the data, so that when the local vector goes out of scope then the input pointer will not be deleted.
To get a C style array out from a C++ vector, use:
1 2 3 |
std::vector<double> input_vector(512); double* pData = input_vector.data(); |
calling the method data() returns a pointer to the first element in the vector. This pointer must never be deleted, the vector will take care of cleaning up its contents.


