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

前端 未结 5 1292
清酒与你
清酒与你 2020-12-02 08:34

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 u

5条回答
  •  温柔的废话
    2020-12-02 09:07

    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.

提交回复
热议问题