Converting std::vector from a C array and vice versa

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:

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:

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.

Facebookgoogle_pluslinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *