Convert between C ++ std :: vector and a C array without copying

I would like to be able to convert between std :: vector and its underlying C int * array without explicitly copying the data.

Does std :: vector provide access to the underlying C array? I'm looking for something like this

vector<int> v (4,100) int* pv = v.c_array(); 

EDIT:

In addition, is it possible to do the opposite, that is, how to initialize std::vector from an array C without copying?

 int pv[4] = { 4, 4, 4, 4}; vector<int> v (pv); 
+45
c ++ c arrays stl stdvector
Nov 14 '09 at 3:33
source share
5 answers

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

 int* pv = &v[0]; 

This pointer is valid only until the vector is redistributed. Redistribution occurs automatically if you insert more elements than will correspond to the remaining capacity of the vector (that is, if v.size() + NumberOfNewElements > v.capacity() . You can use v.reserve(NewCapacity) so that the vector does not have a capacity less than NewCapacity .

Also remember that when a vector is destroyed, the underlying array is also deleted.

+77
Nov 14 '09 at 3:38
source share
 int* pv = &v[0] 

Note that this only applies to std::vector<> , you cannot do the same with other standard containers.

Scott Meyers has extensively covered this topic in his books.
+19
14 Nov '09 at 3:36
source share

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

+15
May 31 '14 at 8:59
source share

If you have very controlled conditions, you can simply do:

 std::vector<int> v(4,100); int* pv = &v[0]; 

We will warn that this will only work until the vector grows, and the vector still controls the lifetime of the base array (that is, do not delete pv). It is not uncommon to do this when calling the base C API, but usually it is done with an unnamed temporary, and not by creating an explicit int * variable.

+14
Nov 14 '09 at 3:37
source share

One way to protect yourself from resizing is to reserve the maximum space (or more) that you will need:

 std::vector<int> v(4,100); //Maybe need v.reserve(40); //reallocate to block out space for 40 elements 

This ensures that push_backs do not redistribute existing data.

0
May 17 '12 at 21:52
source share



All Articles