Converting between C++ std::vector and C array without copying Converting between C++ std::vector and C array without copying arrays arrays

Converting between C++ std::vector and C array without copying


You can get a pointer to the first element as follows:

int* pv = &v[0];

This pointer is only valid as long as the vector is not reallocated. Reallocation happens automatically if you insert more elements than will fit in the vector's remaining capacity (that is, if v.size() + NumberOfNewElements > v.capacity(). You can use v.reserve(NewCapacity) to ensure the vector has a capacity of at least NewCapacity.

Also remember that when the vector gets destroyed, the underlying array gets deleted as well.


In c++11, you can use vector::data() to get C array pointer.


int* pv = &v[0]

Note that this is only the case for std::vector<>, you can not do the same with other standard containers.

Scott Meyers covers this topic extensively in his books.