62

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

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

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

EDIT:

Also, is it possible to do the converse, i.e. how would I initialize an std::vector from a C array without copying?

int pv[4] = { 4, 4, 4, 4};
vector<int> v (pv);
4

5 に答える 5

91

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.

于 2009-11-14T03:38:23.680 に答える
31

c++11 では、vector::data()を使用して C 配列ポインターを取得できます。

于 2014-05-31T08:59:35.490 に答える
20
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.

于 2009-11-14T03:36:01.543 に答える
17

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

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

Be warned that this will only work as long as the vector doesn't have to grow, and the vector will still manage the lifetime of the underlying array (that is to say, don't delete pv). This is not an uncommon thing to do when calling underlying C APIs, but it's usually done with an unnamed temporary rather than by creating an explicit int* variable.

于 2009-11-14T03:37:36.003 に答える
0

サイズの変更から身を守る 1 つの方法は、必要な最大 (またはそれ以上) のスペースを確保することです。

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

これにより、push_backs によって既存のデータが再割り当てされなくなります。

于 2012-05-17T21:52:55.927 に答える